CakePHP: Recursive Finds

(a.k.a It is not a boolean)

Being so new to CakePHP, I’ve spent a lot of time in the documentation. I mean a lot of time. Contrary to popular belief, the documentation is extensive, quite good and covers most, if not all, of the topics I’ve needed help with. One thing I’ve found, though, is that the documentation has three very specific deficiencies in many cases:

  1. Often, only simple cases are covered.
  2. There are a lot of ambiguities that I’d like to see clarified.
  3. It sometimes feels fragmented. The answer I’m looking for often isn’t found in (or even linked from) one place.

Today I ran into the latter two issues when I needed to pull data from an extended model association. I have an Attraction model that has a many-to-many (hasAndBelongsToMany) relationship with an Event model. Each event takes place at a location, so my Event model belongsTo my Location model.

When doing a find ( ‘all’ ) on my Attraction model, each result included, in addition to the Attraction itself, an Event – the model directly associated with with my attraction. I wanted to be able to display Location information as well, so I looked at the recursive parameter in an effort to have find() retrieve data from the extended association.

The find() documentation really provides very little information about the recursive parameter, but there is a syntax example:

'recursive' => 1, //int

When I looked at that, I read it to be a boolean value. To me, the parameter name itself sounds boolean and the only examples I found had a value of 1, a value commonly used (though not explicitly enough for my tastes) to represent a boolean “true”. When I set the parameter to 1, though, I got exactly the same result with the same lack of Location information.

As you may have guessed, I read it wrong. The recursive parameter is really a recursionLevels parameter. Once I set the value to 2, I got information related to the models that were directly associated with the Event model which included my Location information.

This is one of those cases where the documentation isn’t wrong, but it is fragmented and it’s not always easy for new developers to find what they need easily. As I get more familiar with CakePHP, more confident that I know what I’m doing and that I’m doing things the right (read: Cake) way, I’ll do my part to help clarify the documentation where I believe it necessary, but until then I’ll make my notes here in case they can help someone else or someone else can help me.