我有一个posts表和comments表,评论属于帖子,我在帖子和评论模型中设置了关系。我确实按照每个帖子的评论数量对帖子进行排序,如下所示:
$posts = Post::with('comments')->get()->sortBy(function($post) {
return $post->comments->count();
});
我想知道如何对这些排序的帖子进行分页?
$posts = Post::with('comments')->get()->sortBy(function($post) {
return $post->comments->count();
})->paginate(20);
不起作用并给我错误,说分页是一个未定义的方法。
我不知道你是否可以使用 Eloquent 来做到这一点,但你可以使用 join 来做到这一点:
$posts = Post::leftJoin('comments','posts.id','=','comments.post_id')->
selectRaw('posts.*, count(comments.post_id) AS `count`')->
groupBy('posts.id')->
orderBy('count','DESC')->
paginate(20);
然而,在这种情况下,似乎所有记录都是从数据库中获取的,并且仅显示来自分页器的记录,因此,如果您有很多记录,则会浪费资源。看来你应该为此进行手动分页:
$posts = Post::leftJoin('comments','posts.id','=','comments.post_id')->
selectRaw('posts.*, count(comments.post_id) AS `count`')->
groupBy('posts.id')->
orderBy('count','DESC')->
skip(0)->take(20)->get();
using skip
and take
但我不是雄辩专家,也许有更好的解决方案来实现你的目标,所以你可以等待,也许有人会给出更好的答案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)