I have a simple set-up of Albums and Images, each album has many images. I can get all the data fine but I want to limit the returned number of images to 3. I have tried passing a closure like so:
Album::with(['images' => function($query) { $query->take(3);}])->get();
This does limit the number of images to 3 but it limits the total count of images to 3 but I want to limit each album to 3 images. So the first album will show 3 images as expected but all the other albums have no images.
I have tried adding a new method to my model like so:
public function limitImages()
{
return $this->hasMany('App\Image')->limit(3);
}
And I call this in my controller:
Album::with('limitImages')->get();
But this doesn't limit the image count returned at all
$query->limit(3)
in your first Closure attempt, instead oftake(3)
? – SantosAlbum::with('images')->get()
and you only have 3 albums in db (with ids: 1, 2 and 3). Laravel behind the scenes executes next 2 queries: firstselect * from albums
this returns the albums, puts ids in array ([1, 2, 3]) and then it executesselect * from images where in alubm_id [1, 2, 3]
. If you can tell me what SQL to write to limit 2nd query to 3 images per album, I will put it into query builder (I'm good at Laravel - especially Eloquent stuff, not that good with SQL). But I'm pretty sure there isn't an easy way to do this. – Nur@rank := IF(@group = {$group}, @rank+1, 1) as {$rankAlias}, @group := {$group} as {$groupAlias}
you will always need to use raw statements. – NurAlbum
) has a relationship of children (Image
) that's limited to X entries. Only exception is that I uselimit()
instead oftake()
in the->with([...])
function. Maybe an issue with the DB type your using? I'm usingMySQL
, but I don't see where you specify what you're using. – Konikow