【问题标题】:Pagination in CakePHP 2.0CakePHP 2.0 中的分页
【发布时间】:2012-07-20 12:55:24
【问题描述】:

我使用的是 CakePHP 2.x 并且有一个包含许多帖子的线程,我想对其进行分页。但是当我查看 sql-log 时,有一个 SELECT 语句会影响线程的所有帖子(25k)。实际上只显示了 20 个帖子,那么有没有办法避免这种开销?

这是我的 ThreadsController 的代码

public function view($id = null) {
    $this->Thread->id = $id;
    $this->paginate = array(
        'conditions' => array(
            'thread_id' => $id,
        ),
        'order' => array(
            'Post.id' => 'DESC')
    );
    if (!$this->Thread->exists()) {
        throw new NotFoundException(__('Invalid thread'));
    }

    $this->set('thread', $this->Thread->read(null, $id));
    $this->set('posts', $this->paginate('Post'));
}

这是影响所有 25k 行的 SQL 查询:

选择Post.id,Post.user_id,Post.post,Post.created,Post.Post.Post.@987654332 @ FROM ppv3.posts AS Post WHERE Post.thread_id = (1)

【问题讨论】:

  • 您想发布您的代码和 sql 查询吗?如果有一个像你说的那样影响所有人,那是计数查询吗?
  • 编辑了我的问题。不幸的是,这不是计数查询
  • 看起来某处还有另一个查询...您在该操作中拥有的任何内容都不应生成该查询,除非分页出于某种原因忽略了该顺序。
  • 感谢提示,我注释掉了所有与分页相关的代码,查询还在!通过添加“$this->Thread->recursive = 0;”我终于摆脱了它

标签: cakephp


【解决方案1】:

您应该查看您的查询,然后使用 cakePHP 自定义分页方法。 Cakephp Custom Query Pagination。您可以覆盖默认的分页方法。希望这会有所帮助

【讨论】:

  • 感谢您的回答,但解决方案只有一行:“$this->Thread->recursive = 0;”
【解决方案2】:

您的代码一切正常,只是您没有在分页中定义“限制”,即您想为单个页面获取多少条记录。

您的控制器的方法应如下所示:

public function view($id = null) {
$this->Thread->id = $id;
$this->paginate = array(
    'limit' => 20, // this was the option which you forgot to mention
    'conditions' => array(
        'thread_id' => $id,
    ),
    'order' => array(
        'Post.id' => 'DESC')
);
if (!$this->Thread->exists()) {
    throw new NotFoundException(__('Invalid thread'));
}

$this->set('thread', $this->Thread->read(null, $id));
$this->set('posts', $this->paginate('Post'));
}

请询问它是否不适合您。

【讨论】:

  • 嘿,感谢您的回复,但定义“限制”并没有改善。
猜你喜欢
  • 1970-01-01
  • 2012-03-08
  • 1970-01-01
  • 2012-06-27
  • 2012-09-17
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 1970-01-01
相关资源
最近更新 更多