Dec132006

Limiting the associated models returned with CakePHP

Tom OReilly produced a handy solution on the bakery (Keeping bindModel and unbindModel out of your Controllers) to allow to overcome performance issues when querying a model that has a lot of associations with other models. While his solutions prooves useful, I wanted to change it mainly because I didn’t want to have to re-define the way associations are defined on Cake.

So I’ve built a function hooked to AppModel to allow to define what associated models you want to get when querying a model. If you don’t use the function, you get CakePHP’s usual result. If you call it with no parameters, you only get the model you are querying (no associated models.) Finally, you define your relations the normal way.

I’ve produced a tutorial on the bakery that illustrates this: An improvement to unbindModel on model side. It is still pending publication so if you get Article Invalid be patient and try tomorrow :) The following is an example of how you would use it to query the Post model and only get the related author, eventhough the Post model may have associations to other models (such as Category, Comment, etc.)

$this->Post->expects(array('Author'));

$result = $this->Post->findAll();


Leave a Comment

 
Powered by Wordpress and MySQL. Clauz's design for by Cricava