Possible update counterCache Function

I haven’t tested this yet. But it is a possible update counterCache function.
 
<code>
function counterCheck( )
{
 
$counterTemplate =
“UPDATE :atable AS :amodel
SET :counter = (
SELECT COUNT(:model.id)
FROM :table AS :model
WHERE :model.:foreignkey = :amodel.id
)”;
 
$updates = array();
 
$models = Configure::listObjects(‘model’) ;
 
foreach ($models as $model) {
$this->loadModel($model);
$mainTable = Inflector::tableize($model);
if (!empty($this->$model->belongsTo)) {
foreach ($this->$model->belongsTo as $assocModel =>
$def) {
if (isset($def[‘counterCache’]) &&
$def[‘counterCache’]) {
$assocTable =
Inflector::tableize($def[‘className’]);
$assocClass = $def[‘className’];
$foreignKey = $def[‘foreignKey’];
$counter = strtolower($model) . ‘_count’;
$query = String::insert($counterTemplate,
array(
‘table’ => $mainTable,
‘model’ => $model,
‘atable’ => $assocTable,
‘amodel’ => $assocModel,
‘foreignkey’ => $foreignKey,
‘counter’ => $counter
));
$result = $this->Configuration->query($query);
$affectedRows = $this->Configuration-
>getAffectedRows();
$updates[] = array(
‘query’ => $query,
‘affected_rows’ => $affectedRows
);
}
}
}
}
 
$this->set(‘updates’, $updates);
 
}
 
</code>

Related Articles