CacheCounter for HABTM?
Posted on | September 14, 2008 | No Comments
I found out that saving HABTM relationship does not handle the CounterCache automatically.
When saving HABTM relations, the parent table is not updated using the model functions such as save(). The sql statements for the updating are instead generated when the parent’s save() is called. Therefore the cachecounter option does not working for HABTM. The solution is to have an afterSave method in the parent model do the work.
For example, we have features hasAndBelongsToMany categories. The joining primary key table is named features_categories. In the afterSave function for features,
function afterSave() {
App::import('model', 'FeaturesCategory');
$this->FeaturesCategory =& new FeaturesCategory();
$this->FeaturesCategory->updateCounterCacheManual();
return true;
}
In features_categories:
function updateCounterCacheManual() {
$categories = $this->find('all', array('fields' => array('category_id', 'COUNT(*) as count'), 'group' => array('category_id'), 'order' => 'category_id'));
foreach($categories as $category) {
$count = $category[0]['count'];
$this->query("UPDATE categories SET feature_count = $count WHERE id = ".$category['FeaturesCategory']['category_id']);
}
}
The updating statements are not place in feature::afterSave() to keep things encapsulated within the respective models.
In conclusion, CounterCache only works for hasMany relationships. For HABTM, you will have to implement your own.
Comments
Leave a Reply




















