Laravel sortBy paginate

dul*_*lan 5 paginate laravel eloquent laravel-4 laravel-paginate

我有一个帖子表和评论表,评论属于帖子,我在帖子和评论模型中设置了关系.我根据每个帖子的评论数量对帖子进行排序,如下所示:

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

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

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

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

Mar*_*łek 5

我不知道你是否可以使用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);
Run Code Online (Sandbox Code Playgroud)

但是,在这种情况下,似乎所有记录都是从数据库中获取的,并且只显示来自分页器的记录,因此如果您有许多记录,则会浪费资源.看来你应该为此做手工分页:

$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();
Run Code Online (Sandbox Code Playgroud)

使用skiptake,但我不是专家口若悬河,也许有更好的解决方案,以实现自己的目标,所以你可以等待,也许有人会给出更好的答案.