我有以下命令,从我的数据库中获取带有关联 hasMany 条目的条目:
$teasers = $this->Teaser->find('all', array(
'conditions' => array(
'Teaser.published' => 1
),
));
现在,由于hasMany
关系,还将获取posts
条目。
输出如下所示:
array(
0 => array(
'Teaser' => array(
'id' => '1',
'user_id' => '63',
'token' => '56d455bc20cfb56d455bc20d08',
// this goes on
),
'Post' => array(
0 => array(
'id' => '1',
'teaser_id' => '1',
'title' => 'blabla',
'text' => 'blabla',
'published' => 1,
// this goes on
)
)
)
)
现在我的问题是,如何在conditions
中包含一些内容,以过滤Post
条目?
当我像这样输入它时,我收到一个错误:
$teasers = $this->Teaser->find('all', array(
'conditions' => array(
'Teaser.published' => 1,
'Post.published' => 1
)
));
您收到错误的原因是您的关系是hasMany
所以当 Cake 执行contain
时,它实际上是在为您的find
执行多个查询。因此,您无法在条件中指定'Post.published' => 1
,因为主查询(检索预告片的查询)中不存在Post
别名。
相反,您需要将额外条件作为包含的一部分传递:-
$teasers = $this->Teaser->find('all', [
'contain' => [
'Post' => [
'conditions' => [
'Post.published' => 1
]
]
],
'conditions' => [
'Teaser.published' => 1,
]
]);
这将使 Cake 知道您在为帖子构建查询时要使用的条件。
您应该阅读文档以了解可包含和检索的数据。这些是基础知识。
$teasers = $this->Teaser->find('all', array(
'contain' => [
'Post' => [
'conditions' => [
'published' => 1
]
]
],
'conditions' => array(
'Teaser.published' => 1,
)
));
您可以在
模型中编写条件Teaser.php
例如
public $hasMany = array(
'Post' => array(
'className' => 'Post',
'conditions' => array('Post.published' => 1)
)
);