February 23rd, 2009
Ever want to set an attribute in Active Record with a MySQL function? For instance, often times you need to set an attribute to the well known MySQL function “NOW()”. Most people first attempt this in the following way:
<?php $model->createdDate = 'NOW()';
The above, however, will most definitely not work. Why not? Because Yii will first escape the value and then enclose it in quotes, like the following:
... `createdDate`= 'NOW()' ...
Since it is enclosed in quotes, it is treated as a string and not a function. If Yii did not clean the data like this, you would have to, and that would be very annoying.
As of version 1.0.2 of Yii however, there is a way to get around this:
<?php $model->createdDate = new CDbExpression('NOW()');
CDbExpression is a special class for using MySQL expressions in your queries. You use it just like in the above example.