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

查看:26
本文介绍了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')

它仍然返回主记录,当我不想要的时候.

it still returns the primary record, when I dont want it to.

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.

如果是这种情况,您将需要使用 joins() 而不是 contain().

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

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

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.

要做到这一点,只需使用 加入().(创建 MySQL JOIN 的 CakePHP 语法)

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

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

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