3.7.6.7 Multiple relations to the same model
このセクションには保留されている変更があります. More information about translations
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:
<?php
class Message extends AppModel {
var $name = 'Message';
var $belongsTo = array(
'Sender' => array(
'className' => 'User',
'foreignKey' => 'user_id'
),
'Recipient' => array(
'className' => 'User',
'foreignKey' => 'recipient_id'
)
);
}
?>
<?phpclass Message extends AppModel {var $name = 'Message';var $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.
<?php
class User extends AppModel {
var $name = 'User';
var $hasMany = array(
'MessageSent' => array(
'className' => 'Message',
'foreignKey' => 'user_id'
),
'MessageReceived' => array(
'className' => 'Message',
'foreignKey' => 'recipient_id'
)
);
}
?>
<?phpclass User extends AppModel {var $name = 'User';var $hasMany = array('MessageSent' => array('className' => 'Message','foreignKey' => 'user_id'),'MessageReceived' => array('className' => 'Message','foreignKey' => 'recipient_id'));}?>


























