Laravel过滤一对多关系

时间:2018-08-25 19:35:47

标签: laravel eloquent

我有ProductCategory模型一对多地捆绑在一起。如何按类别过滤产品?在模板中,我有

 <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();

2 个答案:

答案 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
    ]);
}