Automate timestamps in ActiveRecord models

You are viewing revision #1 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#3) »

There are dozens of ways to automate the setting of timestamps in yii ActiveRecord models, for example with behaviours or onBeforeSave methods. I sort of like the following method.

To start off we need a database table.

[sql]
CREATE TABLE IF NOT EXISTS `Nodes` (
  `id` bigint(20) NOT NULL auto_increment,
  `title` varchar(255) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

Following this we'll generate the model with the Yii shell tool:

model Node Nodes

To create the crud functionality we need to type this:

crud Node

The magic happens in the rules of the Node class

[php]
/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
	return array(
		array('title','length','max'=>255),
		array('title, created, modified', 'required'),
        array('modified','default','value'=>new CDbExpression('NOW()'),'setOnEmpty'=>false,'on'=>'update'),
        array('created,modified','default','value'=>new CDbExpression('NOW()'),'setOnEmpty'=>false,'on'=>'insert')
	);
}

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.

I find it a simple and elegant solution to this issue.

25 0
35 followers
Viewed: 154 057 times
Version: Unknown (update)
Category: Tutorials
Tags:
Written by: dalip
Last updated by: Yang He
Created on: Feb 14, 2009
Last updated: 5 years ago
Update Article

Revisions

View all history