Bind and contain in cakephp

Cakephp

Posted on 26 Nov 15 by Vickey
  354



In cakephp we can assoceate models together for example I have a tables ‘users’,’posts’,’cources’,’jobs’ and their respecting models ‘ User’,’Post’,’Cource’,’Job’ . One user can have many posts,cources and jobs so I create assoceation between these

class User extends AppModel {
    public $hasMany = array(
    
        'Post' => array(
            'className' => 'Post',
            'foreignKey' => 'user_id',
        ),
        
       'Cource' => array(
            'className' => 'Cource',
            'foreignKey' => 'user_id',
        ),

        'Job' => array(
            'className' => 'Job',
            'foreignKey' => 'user_id',
        ),
    );
    
}

If I do not assoceate these in model  I can assoceate these on the fly in my controller

$this -> User -> bindModel(array(
'hasMany' => array(
    'Post' => array(
        'foreignKey' => 'user_id', 
    ),
    'Cource' => array(
        'foreignKey' => 'user_id', 
    ),
    'Job' => array(
        'foreignKey' => 'user_id', 
    ),

)));
$this->User->find(‘first’,array(‘conditions’=>array(‘User.id’=>1)));

But if I have this assoceation in Model then it will automatically work every where when data User data will be fetch

$this->User->find(‘first’,array(‘conditions’=>array(‘User.id’=>1)));

 

For example I need to retrive user data with his jobs then I use above query it will fetch all assoceated data ‘Post’,’Job’ and ’Cource’ and there is no need others data. So here I can use containable behaviorcontainable behavior to filter my result

$this->User->Behaviors->load('Containable');

$this->User->contain(Job);

$this->User->find(‘first’,array(‘conditions’=>array(‘User.id’=>1)));

We can do this by unbind also


If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com