我有同样的问题。 PawelMysior给出的答案很好,并导致了解决方案。
我在CakePHP书中找到了更多的细节:3.7.4.1.1 counterCache - Cache your count()。这很有帮助,但仍有点模糊。为了其他人的缘故,我想提供一些进一步的细节。
我有两个表:Post和Image。当我向帖子添加图片时,我想跟踪每篇帖子在帖子索引列表中显示的图片数量,而无需在图片表上运行额外的计数查询。
CREATE TABLE posts
(
id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INTEGER UNSIGNED NOT NULL,
title VARCHAR(255),
body TEXT,
created DATETIME,
modified DATETIME,
image_count INTEGER UNSIGNED,
PRIMARY KEY (id)
) ENGINE=InnoDB;
CREATE TABLE images
(
id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
post_id INTEGER UNSIGNED NOT NULL,
filename VARCHAR(255),
created DATETIME,
modified DATETIME,
PRIMARY KEY (id)
) ENGINE=InnoDB;
注意,image_count
云在posts
表。 images
表中没有什么特别的。
class Post extends AppModel
{
var $name = 'Memory';
var $hasMany = array(
'Image' => array(
'className' => 'Image',
'foreignKey' => 'post_id',
'dependent' => false
)
);
}
class Image extends AppModel
{
var $name = 'Image';
var $belongsTo = array(
'Post' => array(
'className' => 'Post',
'foreignKey' => 'post_id',
'counterCache' => true
)
);
}
注意counterCache
被添加到Image
模型。 Post
模型没有什么特别的。
$this->Post->Behaviors->attach('Containable');
$post = $this->Post->find('all', array(
'conditions' => array('user_id' => 7),
'order' => array('Post.created DESC'),
'contain' => array(
'Post' => array(
'User' => array('first_name', 'last_name')
)
)
));
现在,当我们做一个find
没有必要做任何特殊找到计数,因为它会自动在Post
结果的字段。请注意下面的image_count
。
Array
(
[Post] => Array
(
[0] => Array
(
[id] => 14
[user_id] => 7
[title] => Another great post
[body] => Lorem ipsum...
[created] => 2011-10-26 11:45:05
[modified] => 2011-10-26 11:45:05
[image_count] => 21
[User] => Array
(
[first_name] => John
[last_name] => Doe
)
)
)
)
有一点需要注意,如果你添加counterCache到现有的数据库结构,在Post
计数为零,直到另一个Image
加入。此时,CakePHP将执行实际计数并将image_count
更新为正确的数量。
我希望这个额外的信息对某人有帮助。
这是一个不错的主意,但它不能解决更复杂的查询问题,即保持与行关联的计数不起作用(例如用户选择某些条件的报告系统)。有没有其他方法可以使用容易获得计数? – Zxaos 2011-09-15 18:11:05