Laravel 5 Laravel 5.1:雄辩的关系有许多有限的记录

Laravel 5 Laravel 5.1:雄辩的关系有许多有限的记录,laravel-5,Laravel 5,我对Laravel 5.1有一个问题:雄辩的关系有很多限制记录,我有两个表:提要和评论。请求获得5个提要,并对每个特定提要进行相应的评论。我目前正在使用以下查询: public function getFeed($user_id){ return Feed::whereUserId($user_id)->with(['comments'])->take(10)->get()->map(function ($feed) { $feed->com

我对Laravel 5.1有一个问题:雄辩的关系有很多限制记录,我有两个表:提要和评论。请求获得5个提要,并对每个特定提要进行相应的评论。我目前正在使用以下查询:

public function getFeed($user_id){
    return Feed::whereUserId($user_id)->with(['comments'])->take(10)->get()->map(function ($feed) {
        $feed->comments = $feed->comments->take(5);
        return $feed;
    });
}
但是,它会返回所有注释


我的想法是,
$feed->comments=$feed->comments->take(5)行不工作。我只想得到每个饲料5评论,你有什么建议?如有任何意见,我们将不胜感激。谢谢大家!

错误可能就在这里

$feed->comments=$feed->comments->take(5)

应该是哪一个

$feed->comments=$feed->comments->take(5)->get()

我建议你这样写

$feed->load(['comments'=>函数($query){return$query->take(5);}])


通过这种方式,您可以限制所需的提要数量和每个提要的注释数量。

如果它适用于所有情况,您可以像这样调整提要模型中的关系:

public function comments() {
    return $this->hasMany('App\Comment')->limit(5);
}
return Feed::whereUserId($user_id)->take(10)->get()->map(function($feed) {
         $feed->setRelation('comments', $feed->comments->take(5));
         return $feed;
});

迟做总比不做强,我昨天也遇到了同样的问题,最后在模型上设置了整个关系数组

因此,在您的情况下,它将是这样的:

public function comments() {
    return $this->hasMany('App\Comment')->limit(5);
}
return Feed::whereUserId($user_id)->take(10)->get()->map(function($feed) {
         $feed->setRelation('comments', $feed->comments->take(5));
         return $feed;
});

一个多月以来,我一直面临着同样的问题。我只是想优化查询,因为从100万条记录中加载所需数据几乎需要1.5秒

我利用了这个方法。这将加载时间减少到仅300毫秒

就你而言

return Feed::whereUserId($user_id)
    ->get()
    ->each(function ($feed) {
        $feed->load('comments')->take(5);
    })
});

这将限制fid not comments(fid not comments)(fid not comments)(fid not comments)(fid not comments)(fid not comments)(fid not comments)(fid not comments)(fid not comments)(fid not comments)(fid not comments)(fid not comments)(fid not comments)(fid not Comment