有一個疑問,如何通過翻譯關系(按名稱列)過濾結果$item = Cart::select('product_id','quantity')->with(['product.translation:product_id,name','product.manufacturer:id,name'])->where($cartWhere)->get();我的模特Cart.php public function product($language = null) { return $this->hasOne('App\Models\Product','id','product_id'); }Product.php public function translations() { return $this->hasMany('App\Models\ProductTranslation','product_id','id'); }更新v1.0這樣做,但查詢時間太長 $item = Cart::select('product_id','quantity') ->with(['product.translation', 'product.manufacturer:id,name']) ->where($cartWhere) ->when($search,function ($q) use ($search) { $q->whereHas('product.translation', function (Builder $query) use ($search) { $query->where('name', 'like', '%'.$search.'%'); $query->select('name'); }); } ) ->get() ;
1 回答

慕尼黑8549860
TA貢獻1818條經驗 獲得超11個贊
在 with() 方法的數組內,您可以將函數作為值傳遞。
Cart::select('product_id','quantity')
->with([
'product', function($query) {
$query->where($filteringAndConditionsHere);
}
]);
https://laravel.com/docs/7.x/eloquent-relationships#eager-loading
- 1 回答
- 0 關注
- 104 瀏覽
添加回答
舉報
0/150
提交
取消