gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:54:54 24 4
gpt4 key购买 nike

$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 查询。请用 Eloquent 方式解决。

最佳答案

我会这样做👇

数据库结构:

enter image description here

模型货币.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');
}
}

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

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

关于laravel - 如何在 laravel eloquent 的子查询中使用父关系属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44966990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com