How to automate timestamps in ActiveRecord models

There are many ways to automate the setting of timestamps in yii ActiveRecord models. Three are presented here:

  1. Via rules()
  2. Via beforeSave()
  3. Via CTimestampBehavior (zii)

To start off we need to create a database table.

  `id` bigint(20) NOT NULL auto_increment,
  `title` varchar(255) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY  (`id`)

After we have the table we need to create a model and CRUD for it by using Gii.

Check the guide on How to generate model and CRUD with Gii.

The first way you can do it is via your model's rules. Here is an example.

 * @return array validation rules for model attributes.
public function rules()
	return array(
		array('title, created, modified', 'required'),
              'value'=>new CDbExpression('NOW()'),
              'value'=>new CDbExpression('NOW()'),

You see the two rules at the end, one changes the modified field when the record's being updated, and the other changes both fields when the record's being created. You'll also see the "new CDbExpression('NOW()')" statement. This passes "NOW()" to the MySQL server and it will not be escaped. MySQL will interpret it as a statement and not as a string. This means that the field types could have been any other date/time type (timestamp, etc.) and it would still work.

Another solution is to use beforeSave() as follows:

public function beforeSave() {
	if ($this->isNewRecord)
		$this->created = new CDbExpression('NOW()');
		$this->modified = new CDbExpression('NOW()');
	return parent::beforeSave();

Note that in the above code, when creating a new record only the 'created' field will be assigned/updated, while the 'modified' record will be assigned/updated only when updating an existing record.

If you want to assign/update the 'modified' field even when creating a new record... use this code:

public function beforeSave() {
	if ($this->isNewRecord)
		$this->created = new CDbExpression('NOW()');

	$this->modified = new CDbExpression('NOW()');
	return parent::beforeSave();

These are simple and elegant solutions to this issue.

The third possibility is to use CTimestampBehavior in your models. You can read about this in the API documentation:

26 0
Viewed: 179 087 times
Version: 1.1
Category: Tutorials
Written by: dalip
Last updated by: Yang He
Created on: Feb 14, 2009
Last updated: 11 years ago
Update Article


View all history