Search code examples
cakephpmodel-associationscakephp-2.5

Apply where condition on 2nd level association in CakePHP 2.5.x


I want to add a where clause for my 2nd level association in cakephp. In my understanding this should work but it gives me an error

Error: [PDOException] SQLSTATE[42S22]: Column not found: 1054 Unknown column 'User.email_address' in 'where clause'.

$options = array(
    'contain' => array(
        'People',
        'People' => array('User')
    ),
    'conditions'=> array(
        'User.email_address' => '[email protected]'
    ), 
    'recursive' =>1,
);
$query = $this->Organization->find('all', $options);

Solution

  • $options = array(
        'contain' => array(
            'People' => array(
                'User' => array(
                    'conditions'=> array(
                        'User.email_address' => '[email protected]'
                    ),
                ),
            ),
        ),
        //'recursive' =>1,
    );
    $query = $this->Organization->find('all', $options);
    

    Read more:

    http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#containing-deeper-associations