Model “X” with multiple associations leading to Model “Y”
Jimmy Bourassa | February 23, 2009This seems like a fairly common case, but it might not be obvious for everyone. While the title is not totally clear, let’s use an exemple to show where the problem lies.
Let’s say we have a Message model, which has the following fields : id, sender, receiver, created, title, text. We’d like our sender and receiver field to link with our User model, so from and to will contain a user id. If we were to follow CakePHP’s naming convention, we’d have two user_id fields, which is not going to work for obvious reasons. So this is where we have to break CakePHP’s naming convention, which can lead to some confusion. Fear not, the solution is quite simple!
In order for this case to work, all we have to do is change the key in our association :
<?php class Message extends AppModel { var $name = 'Message'; var $belongsTo = array( //In most case, this would be User instead of Sender 'Sender' => array('className' => 'User', 'foreignKey' => 'sender_id' ), //Same goes for Receiver 'Receiver' => array('className' => 'User', 'foreignKey' => 'receiver_id' ), ); } ?>
Once the key is changed, data returned from a find on the Message model will be broke down with these keys we just set.






No need to specify foreignKey. Cookbook: foreignKey: the name of the foreign
Gordon | June 4, 2009No need to specify foreignKey.
Cookbook:
foreignKey: the name of the foreign key found in the current model. This is especially handy if you need to define multiple belongsTo relationships. The default value for this key is the underscored, singular name of the other model, suffixed with ‘_id’.
@Gordon In this case, I am fairly conviced that the foreignKey
Jimmy Bourassa | June 7, 2009@Gordon
In this case, I am fairly conviced that the foreignKey is not optionnal. Notice that the model actually is User but we’re using sender_id and receiver_id as the FKs.