鍍金池/ 問(wèn)答/PHP  數(shù)據(jù)庫(kù)/ Larave with()函數(shù)中正確的limit和take

Larave with()函數(shù)中正確的limit和take

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

//評(píng)論
class comment extends Model
{
    public function essay()
    {
        return $this->belongsTo('App\essay')
    }
}

如何取得每篇文章中的前10條評(píng)論

//這樣寫(xiě)是錯(cuò)的!!! 只能取所有文章的所有評(píng)論的前10條
essay::with(['comment' => function($query) {
    $query->take(10)
}])

求各位大佬幫幫忙

回答
編輯回答
涼心人

with 意味渴求式加載。意思是當(dāng)你需要一些信息的時(shí)候把其連帶的信息也“渴求式的查詢出來(lái)”。所以你要如何取得每篇文章中的前10條評(píng)論那么就要先把所有的文章找出來(lái)然后再去加載每一個(gè)文章的評(píng)論。

essay::get()->comment()->take(10);
2017年3月9日 11:24
編輯回答
薄荷綠

來(lái)自:https://segmentfault.com/a/11... 有兩種方法,自己親測(cè)過(guò)可行,但要注意以下。

//第一種方法,為作者編寫(xiě)的第三種方法。

$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');

//第二種方法則為網(wǎng)址評(píng)論下的第一個(gè)網(wǎng)友(夜影)

2017年9月28日 14:12