CounterCache CakePHP for an existing model

Is there a way to initialize CounterCache on existing data? I refactor my code to use it, and indeed, if I insert a record, it will update the data, but until then it will show 0, which would break other functionality. I was thinking about writing a script to work, but thought there might be a trick?

+3


source to share


1 answer


There are no built-in functions that could magically update all of your models, if that's what you're looking for.

However, you can relatively easily update counter caching manually by using check how uses it on save or delete. Model::updateCounterCache()

Model

Here's a basic example assuming association Article hasMany Comment / Comment belongsTo Article

.



$article = ClassRegistry::init('Article');

foreach(array_keys($article->find('list')) as $id) {
    $article->Comment->updateCounterCache(array(
        $article->Comment->belongsTo['Article']['foreignKey'] => $id
    ));
}

      

This will update all configured counters for all articles in the database (keep in mind that depending on the size of your database, this can be quite a daunting task).

+3


source







All Articles