Jimmie Lin
Jimmie Lin

Reputation: 2215

Get the count sum of an associated model in CakePHP

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!

Upvotes: 3

Views: 1443

Answers (2)

Anh Pham
Anh Pham

Reputation: 5481

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

Upvotes: 1

Stoyan Bozinov
Stoyan Bozinov

Reputation: 39

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

You can find the docs here:

Upvotes: 1

Related Questions