【问题标题】:Laravel nested relation filterLaravel 嵌套关系过滤器
【发布时间】:2020-08-07 13:11:11
【问题描述】:

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

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

【问题讨论】:

  • @xNoJustice 尝试尝试 $item = Cart::select('product_id','quantity') ->with(['product' => function($product) use ($search) { $product->join('product_translations', 'products.id', '=', 'product_translations.product_id'); $product->where( 'product_translations.name', 'LIKE','%'.$search.'%'); }, 'product.manufacturer:id,name']) ->where($cartWhere) ->get(); 但这对我不起作用。不知道为什么,但有时结果收到错误,例如收到的翻译关系不是 product_id

标签: php laravel eloquent orm


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2020-11-22
    • 2017-03-02
    • 2015-10-16
    • 2017-08-03
    • 2022-01-03
    • 2021-06-26
    • 2014-10-27
    • 2020-10-15
    • 1970-01-01
    相关资源
    最近更新 更多