假设我的数据库中有这些关系:
产品
id |名称
类别
id |名称
产品类别
id | product_id | category_id
我可以使用Eloquent的模型通过“ belongsToMany”关系轻松构建它: 产品具有“类别”公共功能,称为“类别”,类别具有“产品”公共功能。
现在,我有一个页面,用户希望通过单击类别名称来过滤给定类别的所有产品。
该程序会将category_id传递给我的控制器,现在开始出现问题。
我可以轻松地“手动”编写此代码:
$products = Product::query()
->leftJoin('product_category', 'product.id', '=', 'product_category.product_id')
->leftJoin('category', 'product_category.category_id', '=', 'category.id')
->where('category_id', '=', 2);
但这会使在Model类中定义关系的过程几乎没有用。
是否有更好的方法可以使用ORM?
非常感谢您!
答案 0 :(得分:1)
使用whereHas
:
$products = Product::whereHas('categories', function ($q) {
$q->where('id', request()->input('category_id'));
})->get();