型号为:stores
和 product
,它们通过以下方式关联:
var $belongsTo = array(
'Store' => array(
'className' => 'Store',
'foreignKey' => 'store_id'
))
var $hasMany = array(
'Product' => array(
'className' => 'Product',
'foreignKey' => 'store_id'
))
我想获得所有商店的列表以及他们拥有的产品数量。我应该如何修改电话:
$this->Store->find('all', array(<..some conditions..>))
返回那种类型的数据?
最佳答案
一种方法是使用 Cake 的内置 counterCache
您的协会中的选项。这可能是性能最高的选项,尽管它确实需要向表中添加一个字段。
在您的 stores
表,添加 INT
字段调用 product_count
在您的 Product
型号添加 counterCache
您协会的选项:
var $belongsTo = array(
'Store' => array(
'className' => 'Store',
'foreignKey' => 'store_id',
'counterCache' => true
));
无论何时添加或删除
Product
记录,它会自动更新product_count
关联字段 Store
记录,以便无需更改您的 find
操作。请注意,如果您选择此路线,您将需要手动更新
product_count
初始值的字段是正确的,因为它只在添加/删除操作后更新。
关于cakePHP - 如何获取相关模型的项目数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8173988/