我们如何在主题控制器中使用分页来执行以下语句


How can we do the following statement in topics Controller with paginate?

我们如何在主题Controller中使用分页执行以下语句?

$posts=$this->Topic->Post->find('all',array('conditions'=>array('Post.t‌​opic_id'=>$id)));

在这里,我的意图是加入Topics和Posts表,使用cakeHP中的paginate()检索Posts表中主题id匹配的帖子数量。

例如,如果主题id 1有n个帖子。如果更改主题id,则该帖子将使用paginate()显示。

您需要使用分页器组件,而不是find:-

$data = $this->Paginator->paginate(
    'Post',
    array('Post.t‌​opic_id' => $id)
);

paginate的第二个参数过滤结果(,即这些是查询条件)。

您还可以向paginate传递与使用$this->paginate处理普通find相同类型的参数。例如:-

$this->paginate = array(
    'conditions' => array('Post.t‌​opic_id' => $id),
    'order' => 'Post.created DESC'
);
$data = $this->Paginator->paginate('Post');

在你的情况下,第一个例子就足够了。

确保在控制器中加载Paginator组件:-

class PostsController extends AppController {    
    public $components = array('Paginator');    
}