A tip on CakePHP find list with related model conditions

You will need to add recursive=>(value) to the $params when you need to get a ‘list’ of table items using related model conditions.

Referring to the example depicted here, http://book.cakephp.org/view/1022/find-list let’s say you perform the following query:

$allPublishedAuthors = $this->Article->find('list', array(
'fields' => array('User.id', 'User.name'),
'conditions' => array('Article.status !=' => 'pending', 'User.status'=>'active'),
'recursive' => 0
));

The query above gives you results just fine. But, there may be an issue when you merely switch to find(‘list’) operation from find(‘all’) operation having $this->Article->recursive=(value 0, 1 etc.) set prior to operation call. Following operation is valid while followed by $this->Article->recursive=(value 0, 1 etc.).

$allPublishedAuthors = $this->Article->find('all', array(
'fields' => array('User.id', 'User.name'),
'conditions' => array('Article.status !=' => 'pending', 'User.status'=>'active'),
));

However the following operation is invalid while followed by $this->Article->recursive=(value 0, 1 etc.) and it gives you the Warning (512): SQL Error: 1054: Unknown column 'User.active' in 'where clause' error.

$allPublishedAuthors = $this->Article->find('list', array(
'fields' => array('User.id', 'User.name'),
'conditions' => array('Article.status !=' => 'pending', 'User.status'=>'active'),
));

To avoid this error you must always add 'recursive' => (value 0, 1 etc.) to the $params of your ‘list’ operation as shown in the very first example above.

I hope this helps someone.

4 thoughts on “A tip on CakePHP find list with related model conditions

  1. helped me a little bit but unfortunately its only going to the next depth. so it works with the next model belongsTo but not over 2 or 3 belongsTo relations..

  2. Brief and clear. Unfortunately, i couldn’t implement it. Simply didn’t work, “Unknown column” errors just kept on coming.

Leave a Reply