Yii2 TimestampBehavior 用来自动给指定的属性填充当前时间戳

要使用 TimestampBehavior,把下面的代码加到你的 ActiveRecord 类中:

use yiibehaviorsTimestampBehavior;

public function behaviors()
{
    return [
        TimestampBehavior::className(),
    ];
}

默认情况下,当关联的 AR 对象执行插入操作时,TimestampBehavior 将会给 created_atupdated_at 两个属性赋值为当前时间戳;而当 AR 对象执行更新操作时, 它只给 updated_at 属性赋值为当前时间戳。时间戳的值来自于 time()

由于属性值是被这个行为自动设置,所以属性值不必用户输入也因此没有必要验证。 因此,created_atupdated_at 这两个属性不应该出现在 rules() 这个模型方法中。

对于应用在 MySQL 数据库的上述实现,请声明 columns(created_at, updated_at) 为整型来存储时间戳。

https://www.yiichina.com/doc/api/2.0/yii-behaviors-timestampbehavior

原文地址:https://www.cnblogs.com/niuben/p/11048569.html