我有Product
和Category
模型一对多地捆绑在一起。如何按类别过滤产品?在模板中,我有
<a href="{{ route('product.productsByCategory', $category->id) }}" class="list-group-item">{{ $category->name }}</a>
如何编写函数来过滤具有类别的产品?
public function productsByCategory($category_id){
$products = Product:: ????
return view("layouts._productsByCategory", compact("products"));
答案是
$products = Product::where('category_id', $category_id)->get();
答案 0 :(得分:2)
您可以使用:
$products = Product::where('category_id', $category_id)->get();
或
$products = Product::whereHas('category', function($q) use ($category_id) {
$q->where('id', $category_id);
});
假设您在category
模型中设置了Product
关系。
答案 1 :(得分:1)
您可能会发现通过类别更容易:
public function productsByCategory($category_id){
return view("layouts._productsByCategory", [
'products' => Category::with('products')->find($category_id)->products
]);
}