1

I need to get brands data in specific collection page but only has more than 1 product.

Here are relations between models.

Brand -> HasMany -> Product

Product <= BelongsToMany => Collection

I was able to get brands data that have more than 1 products for all collections as following:

$brands = Brand::has("products")->get(); //this will return all brands that have more than 1 product.

Now I need to add collection limitation here.

I can get collection from $slug for specific page.

$collection = Collection::where("slug", $slug)->first();

Can anyone please help me how to get brands for specific collection page?

LoveCoding
  • 1,121
  • 2
  • 12
  • 33

1 Answers1

1

Try this:

$brands = Brand::has("products")
->whereHas('products.collections',function($q) use ($slug){ // your relation to product model
  $q->where("slug", $slug);
})
->get();
Yasin Patel
  • 5,624
  • 8
  • 31
  • 53
  • This is great! btw, isn't there any `n+1` query issue? like don't we need to eager load ```products.collections```? – LoveCoding Aug 02 '21 at 07:28
  • 1
    By above query it will join with product and collection record and filter according to critaria, it will get records or brand table and in that you can access product and collection table records – Yasin Patel Aug 02 '21 at 07:31