Gaurav
Gaurav

Reputation: 149

Hasmany relationship for fetching multiple table data

I have three table to store category. One is Primary Category, another is Secondary Category and third is final category. Now I want to get final category with Primary category.

I can get Secondary categories with Primary through relationship by doing this is PrimaryCategory Model:

public function secondaryCategories(){
    return $this->hasMany('App\Models\SecondaryCategory');
}

But Now while getting Secondary Category, I want to get final category in the relation object of Secondary category.

What I mean is Secondary categories should come in the relation object of Primary category and Final category should come in the relation of Secondary Category. How can we do that?

Upvotes: 1

Views: 1027

Answers (2)

Alisha Lamichhane
Alisha Lamichhane

Reputation: 514

You can achieve this by making a small change on your defined method.

Replace this:

public function secondaryCategories(){
    return $this->hasMany('App\Models\SecondaryCategory');
}

To:

public function secondaryCategories(){
    return $this->hasMany('App\Models\SecondaryCategory')->with('finalCategory');
}

And add the following method to your Secondary Category model.

public function finalCategory(){
    return $this->hasMany('App\Models\FinalCategory');
}

This will fetch final category inside the Secondary Category.

Upvotes: 1

Akhtar Munir
Akhtar Munir

Reputation: 1769

Primary Category Model

public function secondaryCategories(){
   return $this->hasMany('App\Models\SecondaryCategory');
}

Secondary Category Model

public function finalCategories(){
   return $this->hasMany('App\Models\FinalCategory');
}

Now while you are getting record from primary category it will become this way

$categories = PrimaryCategory::with('secondaryCategories.finalCategories')->get();

Note this . will create a nesting level like on 1st level you will have primary categories and on second level you will secondary and on 3rd you will have final categories.

You can also load only final categories via secondary categories with hasManyThrough relation

Inside Primary Category Model

public function finalCategories()
{
    return $this->hasManyThrough('App\Models\FinalCategory', 'App\Models\SecondaryCategory');
}

Then do this

$categories = PrimaryCategory::with('finalCategories')->get();

See docs for facing any issue while using different primary keys or foreign keys https://laravel.com/docs/7.x/eloquent-relationships#has-many-through

Upvotes: 1

Related Questions