Lets say we have models User and Friend related by User hasMany Friend relation. If we are required to pull out all users along with their female friends then how do we do that?
Usually people think like this :
$this->User->find('all', array(
'conditions' => array(
'Friend.gender' => 'female'
)));
But the above code will not work. It would normally throw Unknown Friend.gender column error. This is because cakePHP does not make the join yet.
Some programmers try the ad-hoc join something like:
$this->User->find('all', array(
'conditions' => array(
'Friend.gender' => 'female'),
'joins' => array(
array(
'table' => 'friends',
'alias' => 'Friend',
'conditions' => 'Friend.user_id = User.id'
))));
The above code will filter Friend model but the data in User model will be repeated.
Solution:
$this->User->bindModel(array(
'hasMany' => array(
'Friend' => array(
'conditions' =>array('Friend.gender' => 'female'))
)
));
$this->User->find('all');
0 Comment(s)