cakePHP - 如何获取相关模型的项目数?

yos*_*ssi 7 cakephp count model-associations

模型是:storesproduct,它们通过以下方式关联:

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字段以使初始值正确,因为它仅在添加/删除操作后更新.