Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CounterCache CakePHP for existing model

Tags:

cakephp

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?

like image 839
Sela Yair Avatar asked Nov 27 '25 05:11

Sela Yair


1 Answers

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).

like image 122
ndm Avatar answered Dec 01 '25 12:12

ndm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!