Laravel 搜索属于

我正在制作一个搜索功能,并且正在使用 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);

我想以某种方式包含品牌名称,而不是数据库中的品牌 ID。有什么办法可以做到这一点吗?我在我的产品模型中将其像这样链接起来


public function brand()

{

    return $this->belongsTo(Brand::class);

}


婷婷同学_
浏览 118回答 1
1回答

米琪卡哇伊

您可以使用 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);
打开App,查看更多内容
随时随地看视频慕课网APP