Laravel 嵌套关系过滤器

Laravel nested relation filter

有一个查询,如何按翻译关系(按名称列)过滤结果

$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() ;

在 with() 方法的数组内,您可以将函数作为值传递。

Cart::select('product_id','quantity')
    ->with([
         'product', function($query) {
              $query->where($filteringAndConditionsHere);
          }
    ]);

https://laravel.com/docs/7.x/eloquent-relationships#eager-loading