Revision #3 has been created by davi_alexandre on Dec 2, 2011, 4:45:41 PM with the memo:
Just some minor updates in the text
« previous (#2) next (#4) »
Changes
Title
unchanged
Using counters with ActiveRecord
Category
unchanged
Tips
Yii version
unchanged
Tags
unchanged
activerecord, counters, savecounters, updatecounters
Content
changed
[...]
}
```
We have two problems with this approach. All we want is to update the visits column, but the entire record will be updated. Also, if we didn't pass the false argument to the save method, all the validation process will be executed.
Since 1.1.8, the CActiveRecord class has a method that can help us with this task. It's the [CActiveRecord::saveCounters()]
method and its usage is pretty simple:[...]
With this, only the visits column will be updated and the validation will not be triggered.
If you're not using the 1.1.8 yet, there's the [CActiveRecord::updateCounters()] method:[...]
The piece of code above does exactly the same that saveCounters does. Note that updateCounters has two additional parameters. After the column used to count, we pass a condition to tell which record(s) should be updated. If you used any paramater in this condition (like the ":id"), you should pass the parameter value in the third argument of the method.
**Important: If you do not pass a condition, all records will be updated.**