Reputation: 79
I have few products in 3 category (for example), and each product has a brand. I want to show brands which related to products in a specific category.
--product
--brand
--category
category has many products
brand has many products
How can I do that?
Upvotes: 1
Views: 40
Reputation: 9045
Considering you have 3 models with relationships like :
Brand
Model :
public function products()
{
return $this->hasMany(Product::class);
}
Product
Model :
public function brand()
{
return $this->belongsTo(Brand::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
Category
Model :
public function products()
{
return $this->hasMany(Product::class);
}
You can use whereHas
:
$brands = Brand::whereHas('products.category', function ($q){
return $q->where('name', 'category_name');
})->get();
Above will give you all brands which has product belonging to category with name as category_name
.
If you want to get product and category details then you can eager load :
$brands = Brand::whereHas('products.category', function ($q){
return $q->where('name', 'category_name');
})->with(['products', 'products.category'])->get();
Upvotes: 4