Cakephp多对多关系查找条件

Cakephp多对多关系查找条件,cakephp,Cakephp,我需要过滤帖子,这样我才能得到只与类别相关的帖子。我的url将是../posts/index/4 型号: 我的索引代码如下: public function index($cat_id = null) { $this->paginate = [ 'contain' => ['Categories'], 'limit' => 2, 'conditions' =>['Posts.status' => 'publ

我需要过滤帖子,这样我才能得到只与类别相关的帖子。我的url将是../posts/index/4

型号:

我的索引代码如下:

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

我们需要知道您使用的是什么版本的cakephp?我可以假设这是2.x?但是,我不喜欢做假设。很抱歉,这是cakephp 3.2,我忘了提到它。这有点像@chrishick的复制品。谢谢你的链接,我会尝试一下。我已经测试过了,它可以按照你想要的方式工作。类似这样的内容:
$posts\u query=$this->posts->find()->匹配('Categories',函数(\Cake\ORM\query$q)使用($cat\u id){return$q->where(['Categories.id'=>$cat\u id]))->组(['posts.id'])$posts=$this->paginate($posts\u query)