Skip to content
Advertisement

fetch related records between 3 model

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.

Models:

–product

–brand

–category

relations:

category has many products

brand has many products

How can I do that?

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement