【发布时间】: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