Say I have a model Product from a table with id and in_stock fields. I only require to update the the in_stock value to (in_stock + added_stock). Is there a way to update it using the Yii functions without creating an instance of the model? I tried
Product::model()->updateByPk($id,array('in_stock'=>'in_stock+'.$added_stock));
but it didn’t work.
Any solutions are welcome.
I’m guessing you intended that
$added_stockis a local PHP variable? If so this is probably the best way:That should work to add an arbitrary amount to a field without querying the record.
It will also cast the
$added_stockvariable into an integer before hand so there’s no worry of SQL injection or need to place it in a parameter.P.S works with decimals too. Although I don’t think I want to know why you have to deal with fractions of units of stock ?? 🙂