Sorting Related HABTM Model Data With Cake’s Containable Behavior

Posted: November 29th, 2010 | Author: Bret Kuhns | Filed under: Technology | No Comments »

Quite some time ago, Felix Geisendörfer created a behavior for CakePHP called `Containable`, which has since been added to CakePHP’s core. I read about it and it always looked pretty interesting, but I dropped out of the CakePHP realm for a few years while I was busy completing my CSE degree. But now I’m back, and I stumbled upon a need to sort related data from a HABTM relationship. My heart filled with dread as I contemplated the ways to do this, mostly with CakePHP trickery and slow performing SQL queries. But luckily, Containable came to the rescue! I found a blog post that was extremely helpful, but it was written for the pagination helper, which I wasn’t using. So below is the solution rewritten for regular find() calls to a model. Here’s what my association looks like:

Event hasAndBelongsToMany Image

And I needed to make it so that when retrieving an event, the associated Image data was sorted by a specific field. Here’s how to do that using Containable:

public function myAction($order) {
	$this->Event->Behaviors->attach('Containable');
	$this->Event->contain(array(
		'Image' => array(
			'order' => $order
		)
	));

	$event = $this->Event->find('first');

	$this->set(compact('event'));
}

Well that was easy… hopefully I just saved you from a world of hurt.



Leave a Reply