LoveCoding
LoveCoding

Reputation: 1211

Laravel Relationship Query to load hasMany + BelongsToMany

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?

Upvotes: 1

Views: 68

Answers (1)

Yasin Patel
Yasin Patel

Reputation: 5731

Try this:

$brands = Brand::has("products")
->whereHas('products.collections',function($q) use ($slug){ // your relation to product model
  $q->where("slug", $slug);
})
->get();

Upvotes: 1

Related Questions