CakePHP find() 关联条目的条件


CakePHP find() conditions for association entries

我有以下命令,从我的数据库中获取带有关联 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)
    )
);