Difference between #7 and #6 of How to automate timestamps in ActiveRecord models

changed
Title
AutomateHow to automate timestamps in ActiveRecord models
unchanged
Category
Tutorials
unchanged
Tags
unchanged
Content
There are dozens of ways to automate the setting of timestamps in yii
ActiveRecord models. Two ways you can do this are

1. Via rules()
2. Via beforeSave()

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 first way you can do it is via your model's rules.  Here is an
example.

    [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.

Another solution is to use beforeSave() as follows:

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

These are simple and elegant solutions to this issue.
Write new article
  • Written by: dalip
  • Updated by: Yang He
  • Category: Tutorials
  • Yii Version: 1.1
  • Votes: +30
  • Viewed: 103,743 times
  • Created on: Feb 14, 2009
  • Last updated: Jun 29, 2012