cakephp包含关联条件问题 [英] cakephp contain association conditions issue

查看:109
本文介绍了cakephp包含关联条件问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下联想

post-> primary-> secondary

post->primary->secondary

$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
                        (
                        )

                )

        )


推荐答案

知道你希望实现什么,但我想这听起来像你试图限制基于条件对次要模型的主要结果。

It's hard to know exactly what you're hoping to achieve, but I THINK it sounds like you're trying to limit the 'Primary' results based on conditions against the 'Secondary' model.

如果是这样,您将需要使用 join()而不是 contains()

If that's the case, you're going to need to use joins() instead of contain().

原因:当您使用 CakePHP的可容纳行为,它实际上会执行单独的查询,然后在将数据返回给您之前合并结果。这种方法在很多方面都是很好的,但它不允许你根据针对孩子的条件来限制父结果。

The reason: When you use CakePHP's Containable Behavior, it actually does separate queries, then combines the results before returning the data to you. Doing it this way is great in many ways, but it does not allow you to limit parent results based on conditions against it's children.

要使用 joins()。 (CakePHP语法创建MySQL JOIN)

To do that, just use joins(). (CakePHP syntax which creates MySQL JOIN)

这篇关于cakephp包含关联条件问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆