使用 timeStampBehavior
这个行为支持在 Active Record
存储时自动更新它的时间戳属性
namespace app\models\User;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
class User extends ActiveRecord
{
// ...
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
// if you're using datetime instead of UNIX timestamp:
// 'value' => new Expression('NOW()'),
],
];
}
}
以上指定的行为数组:
当记录插入($model->insert()
或$model->save()
)时,行为将当前时间戳赋值给 created_at
和 updated_at
属性;
当记录更新($model->update()
)时,行为将当前时间戳赋值给 updated_at
属性。
使用
$model->save()
更新数据updated_at
不更新
如果更新字段数据没有改变$model->update()
返回0
TimestampBehavior
行为还提供了一个有用的方法 touch()
, 这个方法能将当前时间戳赋值给指定属性并保存到数据库:
$user->touch('login_time');