如何在get()调用中将条件传递给“contains”?

时间:2015-11-13 12:44:03

标签: cakephp orm cakephp-3.0

当获得单个记录和相关记录(两个级别下降)时,我们是否可以将条件传递给CakePHP 3中包含的记录?在这种情况下,例如:

$user = $this->Users->get($this->Auth->user('id'), [
    'contain' => [
        'Articles' => ['Comments']
    ]
]);

如果尝试了一些回调方法,但这似乎只能在第一级工作。像这样,例如:

$user = $this->Users->get($this->Auth->user('id'), [
    'contain' => [
        'Articles' => function ($q) {
            return $q->where(['Articles.published' => true]);
        }
    ]
]);

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

你应该能够做到:

$user = $this->Users->get($this->Auth->user('id'), [
     'contain' => [
        'Articles' => function ($q) {
            return $q->where(['Articles.published' => true]);
        },
        'Articles.Comments' => function ($q) {
            return $q->where(['Comments.deleted' => false]);
        }
    ]
]);

$user = $this->Users->get($this->Auth->user('id'), [
     'contain' => [
        'Articles' => function ($q) {
            $q->contain([
                 'Comments' => function ($q) {
                    return $q->where(['Comments.deleted' => false]);
                }
            ]);
            return $q->where(['Articles.published' => true]);
        }            
    ]
]);

答案 1 :(得分:0)

@ arilia的选项应该可以正常工作。我的偏好是

$user = $this->Users->get($this->Auth->user('id'), [
    'contain' => [
        'Articles' => [
            'queryBuilder' => function ($q) {
                return $q->where(['Articles.published' => true]);
            },
            'Comments' => [
                'querybuilder' => function ($q) {
                    return $q->where(['Comments.deleted' => false]);
                }
            ],
        ],
    ],
]);

(试图将此作为评论发布,而不是单独的答案,但它不会在那里正确格式化代码。)