Flex/Flash Actionscript, JQuery/Javascript, CakePHP

Use a temp primaryKey in model associations for legacy/poorly designed tables

Written by Brandon Plasters on 4/10/10 with 0 Comments
Posted in CakePHP and Backend Development

I needed to associate Models on two tables, tickets and users, but the association was not on the primaryKey it was associated using the ticket.name field: users.ticket_name = tickets.name.

This circumstance unfortunately happens to me often these days. I now work on a database with 100's of tables that needed a re-model years ago, and non-CakePHP coders obliterated the MVC standard AND good database normalization practice in many ways. So there I was, stuck in the non-primary key association complex again and needed a more permanent solution. I thought, wouldn't it be nice to define a temporary primary key override when associating models?

My query needed to be as follows:

SELECT * FROM users
LEFT JOIN tickets on users.ticket_name = tickets.name

then the Model associations will be as follows:

User belongsTo Ticket 

 

in the User model we make a new association option like so:

var $belongsTo = array(
	'Ticket' => array(
		'foreignKey'=>'ticket_name',
		'tempPrimaryKey' => 'name'
	)
)

 

Then in you're AppModel override the __generateAssociation method with the code below:

/** set a temp primary key in the associations in CakePHP 1.2 (and probably CakePHP 1.3 as well)
* @param unknown_type $type
*/
function __generateAssociation($type) {
	parent::__generateAssociation($type);
	foreach ($this->{$type} as $class => $assocData) {
		if(!empty($this->{$type}[$class]['tempPrimaryKey'])){
			$this->{$class}->primaryKey = $this->{$type}[$class]['tempPrimaryKey'];
		}
	}
}

 

Now you can use the tempPrimaryKey field instead of spending days rewriting the system. To re-build this db proplerly would be a dream, and a long- long, long... process. But at least now I have a great legacy tuck-away patch to easily make Model Associations work with tables that should've been rewritten long ago.

Comments

No comments yet. Please do add yours.

Leave a Comment

Please be respectful; your comment my be edited or marked as spam, if necessary.