cook
  • Home
     
  • About Me
     

Model “X” with multiple associations leading to Model “Y”

Jimmy Bourassa | February 23, 2009

This 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.

Comments rss
Comments rss

« Sort search results by relevance Common mistakes when working with accentuated characters »

2 responses

No need to specify foreignKey. Cookbook: foreignKey: the name of the foreign

Gordon | June 4, 2009

No 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.

Leave a comment

You can use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">

Recent Posts

  • OpenX and HostGator shared hosting
  • Common mistakes when working with accentuated characters
  • Model “X” with multiple associations leading to Model “Y”
  • Sort search results by relevance
  • Redirecting to the proper page after actions

People I like

  • Jean-Philippe Doyle
  • Knowland Design
rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox