Category with product by vendor – laravel

I am working on a Laravel with MySQL e-commerce like website, and I can show all the products under its categories by vendor/store.

But the problem is, if I added a product under the same category, it also shows to other vendor which also have that category, that shouldn’t have happen.

My Query:

$categories = Categories::with('products')     ->whereHas('products', function ($query) use ($id) {     $query->where('store_id' ,$id); }) ->get(); 

I think the problem is in the with part? but I don’t know exactly how to do it.

DB Structure:

store  id  |  name   products  id | store_id  | category_id | name   categories id | name 
Asked on September 1, 2020 in Mysql.
Add Comment
1 Answer(s)

WhereHas() check if it has it, but does not filter the result. Does it have a product with this store, if yes return all categories where you now includes products that does not filter.

There is an array syntax, for filtering with() call. This will show the products correctly.

Categories::with(['products' => function ($query) use ($id) {     $query->where('store_id' ,$id); }]) 
Answered on September 1, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.