I've got an Album
model. An Album
can have many Event
and many Picture
but an Event
belongs to one Album
and one Picture
belongs to one Album
too.
I'm trying to make a list of events. In each event, I would like to display album's title and 3 random pictures from this album.
I think I have to use Eager Loading to do so but I'm a little bit confused. Currently I can have a list of albums and take 3 random pictures from them like this:
$albums = Album::with(array('pictures' => function($query) {
$query->orderByRaw("RAND()")->take(2);
}))->get();
foreach ($albums as $album) {
echo $album->title;
foreach ($album->pictures as $picture) {
echo $picture->filename;
}
}
This is working but I have to start from events instead of albums. I don't know how to make all these relations work together. Event -> Album -> Pictures and display them into a view.