Cakephp Classroom image

pankaj
 
To post your Question Join Classroom
 
Lesson Topics's No:-  First|8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16|Last
Lessons:-Models

);
Now that we’ve successfully removed an association on the fly, let’s add one. Our as-of-yet unprincipled
Leader needs some associated Principles. The model file for our Principle model is bare, except for the
public $name statement. Let’s associate some Principles to our Leader on the fly (but remember–only for
just the following find operation). This function appears in the LeadersController:
public function another_action() {
// There is no Leader hasMany Principles in
// the leader.php model file, so a find here,
// only fetches Leaders.
$this->Leader->find(’all’);
// Let’s use bindModel() to add a new association
// to the Leader model:
$this->Leader->bindModel(
array(’hasMany’ => array(
’Principle’ => array(
’className’ => ’Principle’
)
)
)
);
// Now that we’re associated correctly,
// we can use a single find function to fetch
// Leaders with their associated principles:
$this->Leader->find(’all’);
}
There you have it. The basic usage for bindModel() is the encapsulation of a normal association array inside
an array whose key is named after the type of association you are trying to create:
$this->Model->bindModel(
array(’associationName’ => array(
’associatedModelClassName’ => array(
// normal association keys go here...
)
)
)
);
Even though the newly bound model doesn’t need any sort of association definition in its model file, it will
still need to be correctly keyed in order for the new association to work properly.
Multiple relations to the same model
There are cases where a Model has more than one relation to another Model. For example you might have a
Message model that has two relations to the User model. One relation to the user that sends a message, and
a second to the user that receives the message. The messages table will have a field user_id, but also a field
recipient_id. Now your Message model can look something like:class Message extends AppModel {
public $belongsTo = array(
’Sender’ => array(
’className’ => ’User’,
’foreignKey’ => ’user_id’
),
’Recipient’ => array(
’className’ => ’User’,
’foreignKey’ => ’recipient_id’
)
);
}
Recipient is an alias for the User model. Now let’s see what the User model would look like:
class User extends AppModel {
public $hasMany = array(
’MessageSent’ => array(
’className’ => ’Message’,
’foreignKey’ => ’user_id’
),
’MessageReceived’ => array(
’className’ => ’Message’,
’foreignKey’ => ’recipient_id’
)
);
}
It is also possible to create self associations as shown below:
class Post extends AppModel {
public $belongsTo = array(
’Parent’ => array(
’className’ => ’Post’,
’foreignKey’ => ’parent_id’
)
);
public $hasMany = array(
’Children’ => array(
’className’ => ’Post’,
’foreignKey’ => ’parent_id’
)
);
}

 
 
 

pankaj

Skills    Cakephp

Qualifications :-
Location :-,,,
Description:-
Explore
 

  Students (0)