Is there a way to initialize the CounterCache for existing data? I refactor my code to use it and indeed if I insert a record it'll update the data, but until then it shows 0 which will break other functionality. I thought about writing a script to do the work, but thought there might be a trick?
There is not built-in functionality that would magically update all your models if this is what you are looking for.
You can however relatively easily update the counter caches manually using Model::updateCounterCache(), check how the Model uses it on save or delete.
Here's a basic example, assuming an Article hasMany Comment / Comment belongsTo Article association.
$article = ClassRegistry::init('Article');
foreach(array_keys($article->find('list')) as $id) {
$article->Comment->updateCounterCache(array(
$article->Comment->belongsTo['Article']['foreignKey'] => $id
));
}
This would update all configured counters for all articles in the database (keep in mind that depending on the size of your DB this can be quite a heavy task).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With