How can i use parent relation attribute in subquery in laravel eloquent

$order_detail = Order::where([['user_id', $user->id], ['updated_at', '>', $updated_at]])
    ->with([
        'currency'  => function ($query) {
            $query->select('currency_code', 'currency_symbol', 'ex_rate_with_base');
        },
        'orderList' => function ($query) {
            $query->select('id', 'order_id', 'product_code', 'qty',
                DB::raw('(unit_price*orders.ex_rate_with_base) as unit_price_new'), 'status');
        },
    ])->get();

      

Please, help,

How can I use attribute ex_rate_with_base

from table of orders in subquery. I don't want to use a query DB

. Please solve it eloquently.

+4


source to share


1 answer


I would do it like this :)

Database structure:

enter image description here

ModelCurrency.php

class ModelCurrency extends Model
{
    public $timestamps = true;
    protected $table = 'currency';
    protected $guarded = [];
}

      

ModelOrderList.php



class ModelOrderList extends Model{
    public $timestamps = true;
    protected $table = 'order_list';
    protected $guarded = [];
}

      

ModelOrderDetail.php

class ModelOrderDetail extends Model{
    public $timestamps = true;
    protected $table = 'order_detail';
    protected $guarded = [];


    public function scopeOfUser($query, $user_id){
        return $query->where('user_id', $user_id);
    }

    public function scopeUpdatedAfter($query, $updated_at){
        return $query->where('updated_at', '>', $updated_at);
    }


    public function currency(){
        return $this->hasOne(ModelCurrency::class, 'id', 'currency_id');
    }

    public function order_lists(){
        return $this->hasMany(ModelOrderList::class, 'order_id', 'id');
    }
} 

      

Function in the controller:

//imports
use App\ModelOrderDetail;
use Illuminate\Support\Carbon;

public function prices() {
    $user_id = 1;
    $updated_at = Carbon::yesterday();

    $data = ModelOrderDetail::with('currency', 'order_lists')->ofUser($user_id)->updatedAfter($updated_at)->get();

    foreach ($data as $d){
        $base_rate = $d->currency->base_rate;
        foreach($d->order_lists as $o) $o->new_unit_price = $base_rate * $o->unit_price;
    }

    return response()->json($data);
};

      

0


source







All Articles