Abolfazl B
Abolfazl B

Reputation: 79

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?

Upvotes: 1

Views: 40

Answers (1)

Mihir Bhende
Mihir Bhende

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

Related Questions