Larave with()函数中正确的limit和take

//文章
class essay extends Model
{
    public function comment()
    {
        return $this->hasMany('App\comment')
    }
}

//评论
class comment extends Model
{
    public function essay()
    {
        return $this->belongsTo('App\essay')
    }
}

如何取得每篇文章中的前10条评论

//这样写是错的!!! 只能取所有文章的所有评论的前10条
essay::with(['comment' => function($query) {
    $query->take(10)
}])

求各位大佬帮帮忙

阅读 3.7k
3 个回答

来自:https://segmentfault.com/a/11... 有两种方法,自己亲测过可行,但要注意以下。

//第一种方法,为作者编写的第三种方法。

$sub = Comment::whereIn('post_id',$postIds)->select(DB::raw('*,@post := NULL ,@rank := 0'))->orderBy('id');

改为

$sub = Comment::whereIn('post_id',$postIds)->select(DB::raw('*,@post := NULL ,@rank := 0'))->orderBy('post_id');

//第二种方法则为网址评论下的第一个网友(夜影)

with 意味渴求式加载。意思是当你需要一些信息的时候把其连带的信息也“渴求式的查询出来”。所以你要如何取得每篇文章中的前10条评论那么就要先把所有的文章找出来然后再去加载每一个文章的评论。

essay::get()->comment()->take(10);
推荐问题