There are many ways to automatically set the yii timestamp in the ActiveRecord model. The following two methods are described:
There are many ways to automatically set the yii timestamp in the ActiveRecord model. The following two methods are described:
- Use rules ()
- Use beforeSave ()
Create a database table.
?
1234567 |
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; |
In the following method, we will use the Yii shell tool to create a model :?
To create the crud function, we need :?
The first method is to use the rules of your model. Here is an example.
?
12345678910111213141516 |
/*** @ Return array validation rules for model attributes. */publicfunctionrules () {returnarray (array ('title', 'length', 'Max '=> 255), array ('title, created, modified ', 'requestred'), array ('modified', 'default', 'value' => newCDbExpression ('Now () '), 'setonempty' => false, 'on' => 'update'), array ('created, modified', 'default', 'value' => newCDbExpression ('Now ()'), 'setonempty' => false, 'on' => 'insert '));} |
You can see two rules at the end. one rule is to change the attribute value when updating the record, and the other rule is to change the attribute value when creating the record. You can also see the "new CDbExpression (" NOW () ")" statement. This is through the "NOW ()" MySQL server, which will not be avoided. MySQL can translate it as a declaration, not as a string. This means that the field type can be another date/time type (timestamp, and so on), and it can also work.
Another solution is to use the beforeSave () method, using the following:
?
12345678 |
PublicfunctionbeforeSave () {if ($ this-> isNewRecord) $ this-> created = newCDbExpression ('Now () '); else $ this-> modified = newCDbExpression ('Now () '); returnparent: beforeSave ();} |
These are simple and elegant solutions to this problem.