TimestampBehavior支持在 Active Record 更新时自动更新它的时间戳属性。
附加行为到 NewsModel
<?php
namespace common\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
/**
* This is the model class for table "{{%news}}".
*
* @property integer $id
* @property string $title
* @property string $content
* @property string $created_at
* @property string $updated_at
*/
class News extends \yii\db\ActiveRecord
{
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
],
];
}
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%news}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['title'], 'required'],
[['content'], 'string'],
[['created_at', 'updated_at'], 'safe'],
[['title'], 'string', 'max' => 50],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'title' => Yii::t('app', 'Title'),
'content' => Yii::t('app', 'Content'),
'created_at' => Yii::t('app', 'Created At'),
'updated_at' => Yii::t('app', 'Updated At'),
];
}
/**
* @inheritdoc
* @return NewsQuery the active query used by this AR class.
*/
public static function find()
{
return new NewsQuery(get_called_class());
}
}
以上指定的行为数组:
当记录插入时,行为将当前时间戳赋值给 created_at 和 updated_at 属性;
当记录更新时,行为将当前时间戳赋值给 updated_at 属性。
保存 News 对象,将会发现它的 created_at 和 updated_at 属性自动填充了当前时间戳。
$news = new News;
$news ->title = 'Hello TimestampBehavior';
$news ->save();
echo $news ->created_at; // 显示当前时间戳
TimestampBehavior行为还提供了一个有用的方法 TimestampBehavior::touch(),这个方法能将当前时间戳赋值给指定属性并保存到数据库:
$news ->touch('mtime');