How to automate timestamps in ActiveRecord models

Comparing #1 with #3

Revision #3 was created by jonah jonah on Feb 15, 2009, 3:59:16 AM.

typos

Content

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.. Two ways you can do this are
 
 
1. Via rules()
 
2. Via beforeSave()


To start off we need a database table.
[...]
crud Node

The
magic happens in the rules of the Node classfirst way you can do it is via your model's rules.  Here is an example.

[php]
[...]
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 aAnother 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.