Friday, 8 June 2012

Yii Three ways to update counters

Using Yii, there are probably three ways to update counters:

  1. Model->save();
  2. Model->saveCounters();
  3. Model->updateCounters();
For all these methods, we have to get the object before performing the updating process. i.e.,  

$obj = YourObject->model()->findByPk($id);

Difference among them:

1.$obj->visits += 1; 


3.$obj->updateCounters(array('visits'=>'1', 'id'=>$id));

The Trick is:
  1. Better to use saveCounters()!
  2. If you use updateCounters(), pls make sure you have put id in a condition as highlighted in the code. Otherwise, the 'visits' field for all records +1.

1 comment:

  1. Better to use updateCounters() if you don't need to load model.

    Model::model()->updateCounters(array('visits'=>'1', 'id'=>$id));

    If you use save() or saveCounters() you have to send two queries - SELECT and then UPDATE.