Reputation: 350
I'm very new with YII and I don't get it. I have an error with the system that I got. I have to update an SQL rows counter. sql table:
tbl_questions => answercount
I have this code that may modify it:
$model = Questions::model()->findByPk($id);
$model->answercount += 1;
$model->save(false);
The problem is, that: This solution don't do anything. How can I find the problem, or what's the solution? May I could use a good tutorial for this.
Upvotes: 0
Views: 1306
Reputation: 1785
In YII, there are three ways to update counters.
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:
$obj->visits += 1; $obj->save();
$obj->saveCounters(array('visits'=>'1'));
$obj->updateCounters(array('visits'=>'1', 'id'=>$id));
The Trick is:
Better to use saveCounters()
If you use updateCounters()
, make sure you have put id in a condition as highlighted in the code. Otherwise, the 'visits' field for all records +1.
You can also refer this link for more details.
Upvotes: 1
Reputation: 9968
$model->answercount += 1;
$model->attributes = array('answercount' => $model->answercount);
$model->save();
To debug do try the following in your config:
'db'=>array(
…
'enableProfiling'=>true,
'enableParamLogging' => true,
),
Upvotes: 0
Reputation: 19407
There may be one or more errors relating to the save operation. The process you are carrying out should save the updated data to the database, but there may be issues with the update or other errors preventing the save from being carried out.
Try the following
if(!$model->save())
{
throw new Exception("Error saving model : " . var_export($model->getErrors(), true));
}
This will raise an exception if the save operation is failing, and perhaps we can go from there.
Upvotes: 0