Laravel 按分页排序 [英] Laravel sortBy paginate

查看:35
本文介绍了Laravel 按分页排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 posts 表和 comments 表,comment 属于 post,并且我在 Post 和 Comment 模型中有关系设置.我确实按照每个帖子的评论数量对帖子进行了排序,如下所示:

I have a posts table and comments table, comment belongs to post, and I have the relationship setup in Post and Comment model. I did sort posts by the number of comments of each post like this:

      $posts = Post::with('comments')->get()->sortBy(function($post) {
           return $post->comments->count();
      });

我想知道如何对这些排序的帖子进行分页?

What I wonder is how I can paginate these sorted posts?

      $posts = Post::with('comments')->get()->sortBy(function($post) {
           return $post->comments->count();
      })->paginate(20);

不起作用并给我一个错误,说 paginate 是一个未定义的方法.

doesn't work and gives me error that says paginate is an undefined method.

推荐答案

我不知道你是否可以使用 Eloquent 但你可以使用 join 来实现:

I don't know if you can do it using Eloquent but you can use join for this:

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

但是,在这种情况下,似乎所有记录都是从数据库中获取的,并且只显示来自分页器的记录,所以如果您有很多记录,那就是资源浪费.看来您应该为此进行手动分页:

However it seems that in this case all records are taken from database and displayed only those from paginator, so if you have many records it's waste of resources. It seems you should do manual pagination for this:

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

使用 skiptake 但我不是 Eloquent 专家,也许有更好的解决方案可以实现您的目标,因此您可以等待,也许有人会给出更好的答案.

using skip and take but I'm not Eloquent expert and maybe there's a better solution to achieve your goal so you can wait and maybe someone will give a better answer.

这篇关于Laravel 按分页排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆