Let's say I have photos in albums for events.
I want to run:
$photos = Photo::with('albums.events');
Later, I want to run:
foreach($events...)
On JUST the events that belonged to the photos that I found.
What's the best way to accomplish this?
If you have set the relation between the two models :
class Photos extends Eloquent {
public function events() { return $this->hasMany('events'); }
}
You can get the events like if it was normal relations, the eager loading changes nothing about that :
foreach (Photo::with('albums.events')->get as $photo) {
foreach($photo->albums as $album) {
$events = $album->events;
}
}
If you want to simplify your code, you can declare a hasManyThrough
relation :
class Photos extends Eloquent {
public function albums() { return $this->hasMany('Album'); }
public function events() { return $this->hasManyThrough('Event', 'Album');
}
foreach (Photo::with('albums.events')->get as $photo) {
$events = $photo->events;
}
You should take few minutes and read the official doc, this is really helpful.