3

This is a little bit hard to explain, so I'll try to be as clear as possible.

In my CakePHP project, suppose I have a model called Country, and Country has a hasMany association to Region. Now, the Region also has a hasMany association to User, while the country does not (as the Regions can be switched to another country sometime, so associating users to the Country with a foreign key would not be an option).

So, right now, my SQL would look basically like this: (Portions only)

users: id int(16); region_id int(16);
regions: id int(16); country_id int(16);
countries: id int(16);

What I want to do is find a function, or something like counterCache in CakePHP, that I can access through the Countries model and get the count of User in a Region that belongs to a Country. I know that I can just get [User][Country], loop through regions and count it, but is there a cached method for this that (preferably) doesn't require extra code?

Thanks!

Jimmie Lin
  • 2,205
  • 2
  • 23
  • 35

2 Answers2

1

You can do it with find('count', 'recursive'=>2) method

You can find the docs here:

  • Yes, but that can only get me for one region. Adding the sum is what I'm trying *not* to do. Is there a method that does it, for *all* regions, that belong to a country? – Jimmie Lin Aug 04 '11 at 12:10
  • what about http://book.cakephp.org/view/1033/counterCache-Cache-your-count ? there is eben a behavior out there which should be even more powerful. – mark Aug 04 '11 at 12:17
  • try setting the 'recursive' parameter to 2. I have not used it with count, but it works with find('first') to get the objects of a second level relationship. find ('count', array('recursive'=>2)); http://book.cakephp.org/view/1063/recursive – Stoyan Bozinov Aug 04 '11 at 12:28
1

use counterCache on Region, and virtualField('population'=>'SUM(Region.user_count')) (that's just pseudo code!) on Country.

Anh Pham
  • 5,431
  • 3
  • 23
  • 27