当获得单个记录和相关记录(两个级别下降)时,我们是否可以将条件传递给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]);
}
]
]);
有什么想法吗?
答案 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)
$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]);
}
],
],
],
]);
(试图将此作为评论发布,而不是单独的答案,但它不会在那里正确格式化代码。)