0

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);
}
2
  • Do you have a model for clubs and does your association model have a method setup which relates it to clubs? Commented Sep 26, 2016 at 16:42
  • yes, if you need, I can include, it, but relations work. Commented Sep 26, 2016 at 16:42

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

this is exactly what I am doing. I am looking for something to avoid the 2 foreach
Then you can setup a relation in your federation model for clubs which would be a hasManyThrough. laravel.com/docs/5.3/eloquent-relationships#has-many-through
yes, I think this is what I am looking, for, but I am not sure it works with 2 has many relationships
1

You can try the Has Many Through relation ...

which will get you all the clubs that belongs to the associations of the federation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.