场景

在一些表中,记录着此条记录的 添加时间(add_time) 和 更新时间 (update_time)。
开发中,在新增的时候需要将 add_time 置为当前时间,在编辑中需要将 update_time 记录为当前时间。

总是在需要的地方进行手动的维护,是否可以自动维护?

那么就需要使用 TimestampBehavior。

实现原理

在 BaseActiveRecord中

  1. public function init()
  2. {
  3. parent::init();
  4. // 此句话,将会调用 $this->ensureBehaviors(); 届时其所有behaviors的内容将会被初始化
  5. $this->trigger(self::EVENT_INIT);
  6. }

配置

  1. <?php
  2. namespace common\models;
  3. use yii\behaviors\TimestampBehavior;
  4. use yii\db\ActiveRecord;
  5. use yii\db\Expression;
  6. class Banner extends \yii\db\ActiveRecord
  7. {
  8. public function behaviors ()
  9. {
  10. $behaviors = parent::behaviors();
  11. $behaviors = array_merge($behaviors, [
  12. [
  13. 'class' => TimestampBehavior::class,
  14. 'createdAtAttribute' => 'add_time',
  15. 'updatedAtAttribute' => false
  16. ]
  17. ]);
  18. return $behaviors;
  19. }
  20. }

rules 不要有自动注入字段的内容,因为不需要接收用户的值

使用事项

  • rules 不要有自动注入字段的内容,因为不需要接收用户的值
  • 系统默认的字段为 created_at 和 updated_at,如果不是这两个字段的话,需要指定一下,如 指定为 add_time 和 update_time
    • ‘createdAtAttribute’ => ‘add_time’ 以及 ‘updatedAtAttribute’ => ‘update_time’
  • 如果仅有 add_time 没有 update_time,需要设置 update 属性为 false
    • ‘updatedAtAttribute’ => false