场景
在一些表中,记录着此条记录的 添加时间(add_time) 和 更新时间 (update_time)。
开发中,在新增的时候需要将 add_time 置为当前时间,在编辑中需要将 update_time 记录为当前时间。
总是在需要的地方进行手动的维护,是否可以自动维护?
那么就需要使用 TimestampBehavior。
实现原理
在 BaseActiveRecord中
public function init()
{
parent::init();
// 此句话,将会调用 $this->ensureBehaviors(); 届时其所有behaviors的内容将会被初始化
$this->trigger(self::EVENT_INIT);
}
配置
<?php
namespace common\models;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Expression;
class Banner extends \yii\db\ActiveRecord
{
public function behaviors ()
{
$behaviors = parent::behaviors();
$behaviors = array_merge($behaviors, [
[
'class' => TimestampBehavior::class,
'createdAtAttribute' => 'add_time',
'updatedAtAttribute' => false
]
]);
return $behaviors;
}
}
rules 不要有自动注入字段的内容,因为不需要接收用户的值
使用事项
- rules 不要有自动注入字段的内容,因为不需要接收用户的值
- 系统默认的字段为 created_at 和 updated_at,如果不是这两个字段的话,需要指定一下,如 指定为 add_time 和 update_time
- ‘createdAtAttribute’ => ‘add_time’ 以及 ‘updatedAtAttribute’ => ‘update_time’
- 如果仅有 add_time 没有 update_time,需要设置 update 属性为 false
- ‘updatedAtAttribute’ => false