【问题标题】:How to paginate Eloquent query with orderBy. on join如何使用 orderBy 对 Eloquent 查询进行分页。加入时
【发布时间】:2016-08-18 01:12:51
【问题描述】:

在这里,我想要根据每个帖子的 cmets 我一周或一个月的热门帖子。查询正在运行,但我无法分页。请帮忙!

$top = Post::having('created_at', '>=', $time)
        ->selectRaw('posts.*, count(*) as `aggregate`')
        ->join('post_comments', 'posts.id', '=', 'post_comments.post_id')
        ->groupBy('post_id')
        ->orderBy('aggregate', 'desc')
        ->with('post_comments_count')
        ->get();

【问题讨论】:

  • 现在是凌晨 12 点 15 分,谁能帮忙。等待回复。

标签: mysql orm pagination eloquent laravel-5.2


【解决方案1】:

你尝试过 Laravel 的 ->paginate() 命令吗?

$top = Post::having('created_at', '>=', $time)
    ->selectRaw('posts.*, count(*) as `aggregate`')
    ->join('post_comments', 'posts.id', '=', 'post_comments.post_id')
    ->groupBy('post_id')
    ->orderBy('aggregate', 'desc')
    ->with('post_comments_count')
    ->paginate(10);

应该可以正常工作。 在您的刀片文件中,您可以调用分页

{!! $top->links() !!}

来源:Laravel Pagination

【讨论】:

  • 是的,我有,这是我收到的错误消息:(SQLSTATE[42S22]: Column not found: 1054 Unknown column 'created_at' in 'having clause' (SQL: select count(*) as aggregate from posts` 内部连接 ​​post_comments on posts.id = post_comments.post_id posts .deleted_at 为 null 且 confirmed = 0 分组 post_id 具有 created_at >= 2016-04-04))`
  • 您的表“帖子”是否具有 created_at 属性?
  • 是的,但它说只有在我尝试分页时才找到列
  • 很抱歉,感谢您的回复。这不是我的代码中的错误。正如 Laravel 文档中所述 注意:目前,使用 groupBy 语句的分页操作无法被 Laravel 有效执行.如果您需要使用 groupBy 与分页结果集,建议您查询数据库并手动创建分页器。
【解决方案2】:

在使用 groupBy 时需要手动制作 paginator,如Laravel docs! 中所述。

注意:目前,使用 groupBy 语句的分页操作 Laravel 无法有效执行。如果您需要使用 groupBy 带有分页结果集,建议查询 数据库并手动创建分页器。

【讨论】:

    猜你喜欢
    • 2014-10-16
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    相关资源
    最近更新 更多