在 CakePHP 中获取关联模型的计数总和
这有点难以解释,所以我会尽量说得清楚。
在我的 CakePHP 项目中,假设我有一个名为 Country
的模型,并且 Country
与 Region
具有 hasMany
关联。现在,Region
还与 User
具有 hasMany
关联,而国家/地区则没有(因为 Region
有时可以切换到另一个国家/地区,因此不能选择使用外键将用户与国家/地区关联起来)。
所以,现在,我的 SQL 基本上看起来像这样:(仅限部分)
users: id int(16); region_id int(16);
regions: id int(16); country_id int(16);
countries: id int(16);
我想要做的是找到一个函数,或者像 CakePHP 中的 counterCache
之类的东西,我可以通过国家模型访问它获取属于国家/地区
的地区
中的用户
数量。我知道我可以获取 [User][Country],循环遍历区域并对其进行计数,但是是否有一个(最好)不需要额外代码的缓存方法?
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Region 上使用 counterCache,在 Country 上使用 virtualField('population'=>'SUM(Region.user_count')) (这只是伪代码!)。
use counterCache on Region, and virtualField('population'=>'SUM(Region.user_count')) (that's just pseudo code!) on Country.
您可以使用 find('count', 'recursive'=>2) 方法来完成
您可以找到文档 此处:
You can do it with find('count', 'recursive'=>2) method
You can find the docs here: