代码之家  ›  专栏  ›  技术社区  ›  John Jackson

带附加子句的Laravel急加载关系?

  •  0
  • John Jackson  · 技术社区  · 6 年前

    我有两个相关的表格: 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');
        }
    }
    

    User thumbnails 这将允许我立即加载一组特定的a用户 不必先加载所有用户的图像。逻辑如下:

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

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

    使用 debugbar

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

    这只返回 user.thumbnails 第一 Post 缩略图 方法?

    2 回复  |  直到 6 年前
        1
  •  0
  •   lagbox    6 年前

    你的 limit call并没有将1个用户的图片限制为3个,而是将所有帖子的用户图片的整个查询限制为3个。它只会为所有用户找到3张图片。

    你可以把它去掉 限制 目前:

    public function thumbnails()
    {
        return $this->images()->where('processed', true);
    }
    
        2
  •  0
  •   Poldo    6 年前

    您可以在内部查询中调用作用域。

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

    在你的控制器里

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