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

米琪卡哇伊
TA贡献1998条经验 获得超6个赞
您可以使用 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);
- 1 回答
- 0 关注
- 116 浏览
添加回答
举报
0/150
提交
取消