CakePHP:hasmany 关联上的 COUNT 函数
我正在尝试通过 hasmany 关联加入模型,然后计算记录数。基本上我有用户和项目。我想在用户索引操作上显示关联项目的数量。
var $hasMany = array('Project' =>
array('className' => 'Project',
'conditions' => '',
'order' => '',
'limit' => '',
'foreignKey' => 'user_id',
'dependent' => true,
'exclusive' => false,
'finderQuery' => '',
'fields' => '',
'offset' => '',
'counterQuery' => '',
'counterCache' => true
)
);
因此,我已加入 user_id 上的项目模型,并将 counterCache 设置为 true。问题是如何在用户索引视图中访问它?
我已经尝试过了
<?php echo $user['Project']['project_count']; ?>
,
<?php echo $user['User']['project_count']; ?>
有人可以帮助我吗?
琼西
I'm trying to join a model through a hasmany association and then count the number of records. Basically I have users and projects. I want to display the number of associated projects on the user index action.
var $hasMany = array('Project' =>
array('className' => 'Project',
'conditions' => '',
'order' => '',
'limit' => '',
'foreignKey' => 'user_id',
'dependent' => true,
'exclusive' => false,
'finderQuery' => '',
'fields' => '',
'offset' => '',
'counterQuery' => '',
'counterCache' => true
)
);
So I have joined to Project model on user_id and have set the counterCache to true. The question is how do I access this in the user index view?
I've tried
<?php echo $user['Project']['project_count']; ?>
and
<?php echo $user['User']['project_count']; ?>
Can someone help me?
Jonesy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
counterCache
需要位于belongsTo
关联中。在您的示例中,您需要在users
表中拥有project_count
,而在项目模型的关联belongsTo
中,您需要激活counterCache< /代码> 为 true。 查看手册< /a>
counterCache
need to be in thebelongsTo
association. In your example you need to haveproject_count
in theusers
table while in the project model's associationbelongsTo
you need to activate thecounterCache
to true. Check the manual如果您已完成所有这些操作,但 project_count 仍未更新,请尝试关闭 app/config/core.php 中的缓存。
当我更新数据库架构时,我遇到了这个问题,但 Cake 正在缓存旧架构,因此没有计数器字段被发现了。
If you've done all that and the project_count is still not updating, try turning off caching in app/config/core.php
I ran into that issue when I updated the database schema but Cake was caching the old schema and thus no counter field was found.