Welcome to the Cookbook

loading...

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'
        )
    );
}
?>
  1. <?php
  2. class Message extends AppModel {
  3. var $name = 'Message';
  4. var $belongsTo = array(
  5. 'Sender' => array(
  6. 'className' => 'User',
  7. 'foreignKey' => 'user_id'
  8. ),
  9. 'Recipient' => array(
  10. 'className' => 'User',
  11. 'foreignKey' => 'recipient_id'
  12. )
  13. );
  14. }
  15. ?>

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'
        )
    );
}
?>
  1. <?php
  2. class User extends AppModel {
  3. var $name = 'User';
  4. var $hasMany = array(
  5. 'MessageSent' => array(
  6. 'className' => 'Message',
  7. 'foreignKey' => 'user_id'
  8. ),
  9. 'MessageReceived' => array(
  10. 'className' => 'Message',
  11. 'foreignKey' => 'recipient_id'
  12. )
  13. );
  14. }
  15. ?>