Laravel eager load relationship with added clauses?

196 views Asked by At

I have two related tables: Users & Images

class User extends Model
{
    public function images()
    {
        return $this->hasMany('App\Images');
    }
}

class Image extends Model{

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

I'm attempting to add a second method on the User model named thumbnails that would allow me to eager load a specific set of a users Images without having to load all of the users images first. Here is the logic:

public function thumbnails () {
    return $this->hasMany('App\Images')
        ->selectRaw('src, user_id')
        ->where('processed', true)
        ->limit(3);
}

Here is how I've been calling this relation:

$posts = Post::with(['user','user.thumbnails'])->get();

using debugbar, I was examine the query:

"sql": "select src, user_id from \"images\" where \"processed\" = 1 and \"images\".\"user_id\" in (12, 14, 15) limit 3", 

This only returns the user.thumbnails first Post model. Is there an issue with my thumbnails method ?

2

There are 2 answers

2
Poldo On

You can call scope in inner query.

class User extends Model{

    public function scopeThumbnails($query)
    {
        return $query->where('processed', true)
        ->limit(3);
    }
}

in your controller

$posts = Post::with(['user' => function($query) {
    $query->thumbnails();
}])->get();
1
lagbox On

Your limit call isn't limiting 1 user's images to 3, it is limiting the entire query for all the posts' users' images to 3. It will only find 3 total images for all the users.

You can remove that limit for now:

public function thumbnails()
{
    return $this->images()->where('processed', true);
}