0

I need to filter posts so that I get posts only related to category. My url will be ../posts/index/4

Models:

Snapshot

My code for index is as follows:

public function index($cat_id = null)
{
    $this->paginate = [
        'contain' => ['Categories'], 
        'limit' => 2,
        'conditions' =>['Posts.status' => 'publish'],
        //'conditions' =>['PostsCategories.category_id' => '4'],
        'order' => ['Posts.createdAt' => 'desc'],
        'fields' => [
            'Posts.id', 
            'Posts.title', 
            'Posts.excerpt', 
            'Posts.author', 
            'Posts.location', 
            'Posts.date',
            'Posts.main_pic',
            'Posts.hits'
        ],
    ];

    $posts = $this->paginate($this->Posts);     

    $nextPage = $this->request->params['paging']['Posts']['nextPage'];

    $this->set(compact('posts'));
    $this->set(compact('nextPage'));
    $this->set('_serialize', ['posts', 'nextPage']);
}
sharvil111
  • 4,301
  • 1
  • 14
  • 29
PDM
  • 31
  • 1
  • 5
  • We need to know what version of cakephp you are using? I can assume this is 2.x? But, I don't like to make assumptions. – chrisShick Mar 28 '16 at 16:25
  • it is cakephp 3.2, sorry, that I forgot to mention it. – PDM Mar 28 '16 at 16:53
  • 1
    This is somewhat of a duplicate of http://stackoverflow.com/questions/29737422/conditions-to-paginate-for-belongstomany-cakephp-3 – chrisShick Mar 28 '16 at 17:13
  • @chrisShick thanks for the link, I will try it – PDM Mar 28 '16 at 18:14
  • I already tested it and it works the way you want it to. Something like this: `$posts_query= $this->Posts->find()->matching('Categories', function(\Cake\ORM\Query $q) use($cat_id) { return $q->where(['Categories.id' => $cat_id]); })->group(['Posts.id']); $posts = $this->paginate($posts_query);` – chrisShick Mar 28 '16 at 18:55

0 Answers0