cakephp包含关联条件问题

时间:2012-10-31 18:28:35

标签: cakephp

我有下列协会

后>伯 - >仲

$results = $this->Post->find('all', array(
    'conditions' => array(
        'Post.post_id =' => 2,
        'Primary.secondary_id !=' => null
    ),
    'contain' => array(
        'Primary' => array(
            'Secondary' => array(
                'conditions' => array('Secondary.short_code =' => 'code')
            )
        )
    )
));

返回此内容。

Array
(
    [0] => Array
        (
            [Post] => Array
                (
                    [id] => 2
                    [created] => 2012-10-29 09:48:29
                    [modified] => 2012-10-29 09:48:29
                )

            [Primary] => Array
                (
                    [id] => 3
                    [secondary_id] => 6
                    [Secondary] => Array
                        (
                            [id] => 6
                            [short_code] => code
                            [created] => 2012-10-31 11:19:56
                            [modified] => 2012-10-31 11:20:03
                        )

                )

        )

然而,当我改变

'conditions' => array('Secondary.short_code =' => 'code')

'conditions' => array('Secondary.short_code !=' => 'code')

当我不想要它时,它仍会返回主记录。

Array
(
    [0] => Array
        (
            [Post] => Array
                (
                    [id] => 2
                    [created] => 2012-10-29 09:48:29
                    [modified] => 2012-10-29 09:48:29
                )

            [Primary] => Array
                (
                    [id] => 3
                    [secondary_id] => 6
                    [Secondary] => Array
                        (
                        )

                )

        )

1 个答案:

答案 0 :(得分:5)

很难确切地知道你希望实现的目标,但我认为这听起来像是你试图根据“辅助”模式的条件限制“主要”结果。

如果是这种情况,您将需要使用joins()代替contain()

原因:当您使用CakePHP's Containable Behavior时,它实际上会执行单独的查询,然后在将数据返回给您之前合并结果。这样做在很多方面都很棒,但是它不允许你根据对孩子的条件来限制父结果。

为此,请使用joins()。 (创建MySQL JOIN的CakePHP语法)