0
votes

I am new to CAKEPHP and using joins for the first time. I read the documentation as well.

Now i have two models, One is for Users and other is for Status.

In Status table i have a foreign Key which is User Id in users table.

I want to use $hasMany with conditions such that if a logged in user Share a status it should update the status table having UID in the foreign key and UID is Users table primary key

I dont know what and how to do that.

What i believe is that it should be something like this

class User extends AppModel 
{    
    var $name = 'User';    
    var $hasMany = array(
    'Status' => array( 
    'conditions' => array('Status.FK' => 'User.id') 
       )
    );
}

Hope i did it right?

1

1 Answers

3
votes

for hasMany put this code in your User Model:

/**
 * @see Model::$hasMany
 */
    public $hasMany = array(
        'Status' => array(
            'className' => 'Status',
            'foreignKey' => 'Status.FK',
            'dependent' => true,
        ),
    );

but The Best way is that using belongsTo in your Status Model,Because belongsTo has fewer queries than hasMany method. and in your controller you can use the Status model to retrieving users with their status. for example: In Status Model:

/**
 * @see Model::$belongsTo
 */
    public $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'Status.FK',
        ),
    );

then In your Controller for find specific rows from database you can use :

    $this->recursive = 1;
    $this->Status->find('all',array('conditions' => array('User.id' => $id)));