Working with Associations using CakePHP

I was asked by Niraja Mulye of Packt Publishing if I would be interested in publishing an article on my blog from the book, CakePHP Application Development. Since it seems relevant to any starting out with CakePHP, I guess why not.

Instead of copying and pasting what was sent, I found two articles which seemed like the original source. Being properly formatted, I guess it will be more appropriate for me to point them to you. The first article titled, Working with Simple Associations using CakePHP talks about the basic belongsTo, hasOne and hasMany assocations while the second article titled, Working with Complex Associations using CakePHP tackles the hasAndBelongsToMany association where most beginners have difficulty with.

The articles will be useful for anyone starting out but unfortunately, CakePHP had gone through lots of changes and the book (published on July 2008) is based on an older version of CakePHP. So now there are actually better ways of dealing with associations using the Containable Behavior. The Containable Behavior binds and unbinds model on the fly, automatically setting the recursive level to suit. This means you no longer have to bother about setting the recursive level as long as you “contain” your find() queries. I am mentioning this because I have to warn against the setting of recursive level directly.


// All models have recursive level set to 1 by default
$this->Author->recursive = 2;
$this->Author->id = 1001;
$this->Author->find('first'); // Return results based on recursive level of 2
// some
// codes
// in
// between
$this->Author->find('all'); // Return results based on recursive level of 2 (as set previously) and not 1!

This causes CakePHP to retrieve more data than it should when it is unintended by you. My suggestion is to have all models default to recursive level -1 by setting it in the AppModel and let “contain” handle the rest.


$this->Author->id = 1001;
$this->Author->find('first', array('contain' => 'Book')); // Returns author 1001 and all books authored by him/her
$this->Author->find('all'); // Returns all authors only

How nice!

Bookmark and Share
This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.
  • http://cairorichardson.posterous.com/ Linus Ramsey

    CakePHP is the capability to link relational applying offered by the design. In CakePHP, the hyperlinks between designs are managed through Association.