There are many ways to automate the setting of timestamps in yii ActiveRecord models. In this we are representing three ways here.
1) Update via model’s rules:
[php]
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
return array(
array(‘title’,’length’,’max’=>255),
array(‘title, created_at, updated_at’, ‘required’),
array(‘updated_at’,’default’,
‘value’=>new CDbExpression(‘NOW()’),
‘setOnEmpty’=>false,’on’=>’update’),
array(‘created_at,updated_at’,’default’,
‘value’=>new CDbExpression(‘NOW()’),
‘setOnEmpty’=>false,’on’=>’insert’)
);
}
[/php]
2) Another to use beforeSave() as follows:
[php]
public function beforeSave() {
if ($this->isNewRecord)
$this->created_at = new CDbExpression(‘NOW()’);
$this->updated_at = new CDbExpression(‘NOW()’);
return parent::beforeSave();
}
[/php]
3) Another alternative to use CTimestampBehavior in your models:
[php]
public function behaviors()
{
return array(
‘CTimestampBehavior’=>array(
‘class’=>’zii.behaviors.CTimestampBehavior’,
‘createAttribute’=>’created_at’,
‘updateAttribute’=>’updated_at’,
‘setUpdateOnCreate’=>true,
‘timestampExpression’=>new CDbExpression(‘NOW()’);
)
);
}
[/php]
Note: Instead of using NOW(), you can also use UTC_TIMESTAMP().