如何在laravel eloquent中的子查询中使用父关系属性

时间:2017-07-07 09:14:56

标签: laravel laravel-5 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();

请帮忙,

如何在子查询中使用订单表中的属性ex_rate_with_base。 我不想使用DB查询。请用雄辩的方式解决。

1 个答案:

答案 0 :(得分:1)

我会这样做

数据库结构:

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');
    }
} 

控制器中的功能

//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);
};

编辑-输出:https://pastebin.com/i53PytSk