我正在做一个搜索功能,我正在使用orWhere,然而,我遇到了一个问题,我想通过文本搜索brand_id。在我的模式中,我将其设置为belongsTo,但是有什么方法可以在MySQL搜索项中使用它吗?
我的搜索查询
$products = Product::where('name', 'LIKE', '%' . $searchTerm . '%')
->orWhere('title', 'LIKE', '%' . $searchTerm . '%')
->orWhere('description', 'LIKE', '%' . $searchTerm . '%')
->orWhere('allergies', 'LIKE', '%' . $searchTerm . '%')
->orWhere('price', 'LIKE', '%' . $searchTerm . '%')->paginate(15);我想以某种方式包括品牌名称,而不是我在数据库中的brand_id。有什么方法可以做到这一点吗?我在我的产品模型中把它像这样链接起来
public function brand()
{
return $this->belongsTo(Brand::class);
}发布于 2020-07-19 09:34:25
您可以使用orWhereHas:
$products = Product::where('name', 'LIKE', '%' . $searchTerm . '%')
->orWhere('title', 'LIKE', '%' . $searchTerm . '%')
->orWhere('description', 'LIKE', '%' . $searchTerm . '%')
->orWhere('allergies', 'LIKE', '%' . $searchTerm . '%')
->orWhere('price', 'LIKE', '%' . $searchTerm . '%')
->orWhereHas('brand', function($q) use ($searchTerm){
$q->where('name', 'LIKE', "%{$searchTerm}%");
})
->paginate(15);https://laravel.com/docs/master/eloquent-relationships#querying-relationship-existence
https://stackoverflow.com/questions/62975347
复制相似问题