Let's say I have athletes who belong to photos that belong to albums that belong to events.
The fastest method for getting photos of an athlete is $athlete->photos;
If I go this direction:
$events= Event::whereHas('albums.photos.athletes', function ($q)
{
$q->where('athlete_id', $this->athlete->id);
})
It works, but slower, and I'm not able to do things like $events->albums and only return albums that have photos of this particular athlete.
On my page, I want to display photos by event. How can I use $athlete->photos
and then organize them by event?
I could loop through all of the photos found from $athlete->photos
and build a new array with the hierarchy of event->album->photo but that seems really janky. Is there a better way to do this using Eloquent?
Edit:
This returns EXACTLY the data I need without the need for further queries, but it takes almost 20 seconds to finish.
// Get all athlete media
$competitions = Competition::whereHas('publishedAlbums.publishedMedia.athletes', function ($q)
{
$q->where('athlete_id', $this->athlete->id);
})
->with(array('publishedAlbums.publishedMedia' => function($query)
{
$query->whereHas('athletes', function ($q)
{
$q->where('athlete_id', $this->athlete->id);
});
}))
->with(array('publishedAlbums' => function($query)
{
$query->whereHas('publishedMedia.athletes', function ($q)
{
$q->where('athlete_id', $this->athlete->id);
});
}))
->get();
With that, I can do things like $competitions->publishedAlbums and it only shows albums that have media for this athlete. BUT it takes a very long time to execute.