Search code examples
phpcakephphas-many

CakePHP - Find hasMany association without hasMany relation in Model?


Again I want ask you a question about CakePHP : I have 2 model User and Comment with relation 1-n (One User have many Comment). I want use find() to list infomation both user and it's comments with format data return :

Array
(
    [User] => Array
        (
            [id] => 121
            [name] => Gwoo the Kungwoo
            [created] => 2007-05-01 10:31:01
        )
    [Comment] => Array
        (
            [0] => Array
                (
                    [id] => 123
                    [user_id] => 121
                    [title] => On Gwoo the Kungwoo
                    [body] => The Kungwooness is not so Gwooish
                    [created] => 2006-05-01 10:31:01
                )
            [1] => Array
                (
                    [id] => 124
                    [user_id] => 121
                    [title] => More on Gwoo
                    [body] => But what of the 'Nut?
                    [created] => 2006-05-01 10:41:01
                )
        )
)

But I don't want to config relationship hasMany in model User as example in link : http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html. I tried this code :

 $data = $this->User->find('all', array(
                'joins' => array(
                    array(
                        'table' => 'comment',
                        'alias' => 'Comment',
                        'type' => 'LEFT',
                        'conditions' => array(
                            'User.id = Comment.user_id'
                        )
                    ),
                    'conditions' => array(
                       'User.id' => $userId
                    ),
                     'fields' => array('User.*', 'Comment.*')
            ));

And Cake return an array with duplicate record of user (Ex : if user has 2 comments, it returns 2 records of user duplicate).

Anyone can give me another solution for this ? ( but except solution that config hasMany relation model), thanks.


Solution

  • Alternatively you can use bindModel in your controller

            $this->User->bindModel(
                   array(
                     'hasMany'=>array(
                         'Comment' =>array(
                          'className' => 'Comment',
                          'foreignKey' => 'user_id',
                          'conditions' => array('Comment.status' => 'Active'),
                      )         
                   )
                )
            ); 
    
            $data = $this->User->find('all',array('conditions'=>array('User.email'=>$userEmail)));
    

    For more info

    UPDATED

    Have a look at this answer for some info, see details about bind and unbind model through this link