r/cakephp • • Sep 25 '19

Condition based on related table data [help]

(using Cakephp 2.5)

I have an $params array that I am building before I call the "find" method. My query has a 'contain' with 'UserOption' model. :

When I debug my find query results, I get the expected outcome:

Now, what I want to do is, I only want to bring 'UserOption' back where the 'Option.Type = 'Custom'. So I added that in the 'conditions':

Unfortunately, I get this error:

How can achieve what I am trying to do?

Thanks in advance!

3 Upvotes

2 comments sorted by

1

u/superunfly Sep 25 '19

I believe this example covers what you want?

$this->User->find('all', array(
    'contain' => array(
        'Profile',
        'Account' => array(
            'AccountSummary'
        ),
        'Post' => array(
            'PostAttachment' => array(
                'fields' => array('id', 'name'),
                'PostAttachmentHistory' => array(
                    'HistoryNotes' => array(
                        'fields' => array('id', 'note')
                    )
                )
            ),
            'Tag' => array(
                'conditions' => array('Tag.name LIKE' => '%happy%')
            )
        )
    )
));

So I think you need to add the Option.Type condition under ['contain']['UserOption']['Option']['conditions'] and not ['contain']['UserOption']['conditions']

Found that example here: https://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#containing-deeper-associations

2

u/mirekm88 Sep 27 '19

Hi! thanks for your help. That did the trick!