How can we do the following statement in topics Controller with paginate?
$posts=$this->Topic->Post->find('all',array('conditions'=>array('Post.topic_id'=>$id)));
Here my intention is that join the Topics and Posts tables, retrive the no of posts where topic id is matching in the posts table using paginate()
in cakePHP.
For example if topic id 1 have n no of posts. if change the topic id, that belongs posts will display using paginate()
.
You need to use the paginator component rather than a find
:-
$data = $this->Paginator->paginate(
'Post',
array('Post.topic_id' => $id)
);
The second parameter of paginate
filters the result (i.e. these are the query conditions).
You can also pass the same sort of parameters to paginate
as you would with a normal find
using $this->paginate
. For example:-
$this->paginate = array(
'conditions' => array('Post.topic_id' => $id),
'order' => 'Post.created DESC'
);
$data = $this->Paginator->paginate('Post');
In your case the first example should be sufficient.
Make sure you load the Paginator
component in your controller:-
class PostsController extends AppController {
public $components = array('Paginator');
}