CakePHP 2.0中的分页

时间:2012-07-19 20:29:53

标签: cakephp

我使用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查询:

选择PostidPostuser_idPostpostPost。{{1} },createdPostmodifiedPost FROM thread_idppv3 AS posts WHERE PostPost =(1)

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

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

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'));
}

请问它是否对您不起作用。