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 Region
s 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!
use counterCache on Region, and virtualField('population'=>'SUM(Region.user_count')) (that's just pseudo code!) on Country.
You can do it with find('count', 'recursive'=>2) method
You can find the docs here:
精彩评论