yos*_*ssi 7 cakephp count model-associations
模型是:stores
和product
,它们通过以下方式关联:
var $belongsTo = array(
'Store' => array(
'className' => 'Store',
'foreignKey' => 'store_id'
))
var $hasMany = array(
'Product' => array(
'className' => 'Product',
'foreignKey' => 'store_id'
))
Run Code Online (Sandbox Code Playgroud)
我想获得所有商店的清单以及他们拥有的产品数量.我该如何修改调用:$this->Store->find('all', array(<..some conditions..>))
返回那种类型的数据?
Dou*_*ngs 17
一种方法是counterCache
在关联中使用Cake的内置选项.这可能是性能最高的选项,但它确实需要在表中添加一个字段.
在stores
表格中,添加一个INT
名为的字段product_count
在您的Product
模型中,counterCache
为您的关联添加选项:
var $belongsTo = array(
'Store' => array(
'className' => 'Store',
'foreignKey' => 'store_id',
'counterCache' => true
));
Run Code Online (Sandbox Code Playgroud)
无论何时添加或删除Product
记录,它都会自动更新product_count
相关Store
记录的字段,因此无需更改find
操作.
请注意,如果选择此路由,则需要手动更新product_count
字段以使初始值正确,因为它仅在添加/删除操作后更新.
归档时间: |
|
查看次数: |
7966 次 |
最近记录: |