Reputation: 19725
I need to get all clubs that belongs to a federationPresident.
So, I have:
$federation->associations
which gets me a collection of associations,
$association->clubs that gives me a collection of clubs
I would like to do :
$federation->associations->clubs, but it doesn't work
What I did:
foreach ($federation->associations as $association) {
foreach ($association->clubs as $club){
$clubs->push($club);
}
}
This works, but I think I'm missing something, and I could do it easilier.
Thing is I will have to do it a lot of time in my code, so, this is not very elegant...
Any Idea how to do it better?
Association Model:
public function clubs()
{
return $this->hasMany(Club::class);
}
Upvotes: 0
Views: 613
Reputation: 33108
You can use eager loading. You use dot notation to relate nested models.
$federations = Federation::with('associations.clubs')->get();
And now everything is nested for you...
foreach ($federations as $federation) {
foreach ($federation->associations as $association) {
foreach ($assocation->clubs as $club) {
...
}
}
}
Another way would be to use the hasManyThrough
relating method. It does work with 2 has-manies.
In your Federation
model.
public function clubs()
{
return $this->hasManyThrough(Club::class, Association::class);
}
Upvotes: 1
Reputation: 1454
You can try the Has Many Through
relation ...
which will get you all the clubs that belongs to the associations
of the federation
Upvotes: 1