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
2 Comments »
Comments rss Comments rss

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