Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to filter hasMany related model records in cakePHP when using find function?

    • 0
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.01k
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: