1
votes

Let's suppose I have these relations in my DB:

Product

id | name

Category

id | name

Product-Category

id | product_id | category_id


I can easily build it using Eloquent's Models using "belongsToMany" relations: Product has a "categories" public function called "categories" and Category has a "products" public function.

Now, I have a page where the user wants to filter all the products for a given category by clicking on the category name.

The program will pass the category_id to my Controller and now begins the problem.

I can easily do it "by hand" writing this code:

            $products = Product::query()
            ->leftJoin('product_category', 'product.id', '=', 'product_category.product_id')
            ->leftJoin('category', 'product_category.category_id', '=', 'category.id')
            ->where('category_id', '=', 2);

But this would make the process of defining the relation in the Model class almost useless.

Is there a better way of making it, maybe using the ORM stuff?

Thank you so much!

1

1 Answers

1
votes

Use whereHas:

$products = Product::whereHas('categories', function ($q) {
    $q->where('id', request()->input('category_id'));
})->get();

See Querying Relationship Existence.