Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

cakephp contain association conditions issue

I have the folowing associations

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')
            )
        )
    )
));

Returns this.

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
                        )

                )

        )

However when I change

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

to

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

                )

        )
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...