3
votes

I'm pretty new to CakePHP but I think I'm starting to get the hang of it. I'm trying to pull related table information recursively, but I want to specify which related models to recurse on. Let me give you an example to demonstrate my goal:

I have a model "Customer", which has info like Company name, website, etc. "Customer" hasMany "Addresses", which contain info for individual contacts like Contact Name, Street, City, State, Country, etc. "Customer" also belongsTo "CustomerType", which is just has descriptive category info - a name and description, like "Distributor" or "Manufacturer".

When I do a find on "Customer" I want to get associated "CustomerType" and "Address" info as sub-arrays, and this works fine just by setting up the hasMany and belongsTo associations properly. But now, here's my issue: I want to get associated State/Country info. So, instead of each "Address" array row just having "state_id", I want it to have "state" => array("id" = 20, "name" = "New York",...) etc.

If I set $recursive to a higher value (e.g., 2) in the Partner model, I get what I want for the State/Country info in each "Address". BUT it also recurses on "CustomerType", and that results in the "CustomerType" field of my "Partner" object having a huge array of all Customer objects that match that type, which could be thousands long.

So the point is, I DON'T want to recurse on "CustomerType", only on "Address". Is there a way I can set this up?

Sorry for the long-winded question, and thanks in advance!

2

2 Answers

9
votes

I suggest you use the "Containable" behaviour; see more help on the cake site in the book: http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html

3
votes

Sometimes containable generates too many queries. Another option to achieve what you want is to unbind CustomerType model. You can find more details here: http://teknoid.wordpress.com/2008/07/17/forcing-an-sql-join-in-cakephp/, http://mark-story.com/posts/view/using-bindmodel-to-get-to-deep-relations.