在开发过程中,经常会忘了给创建时间、更新时间等字段赋值,这里介绍两种自动更新时间的方法:
方法一:beforeSave
public function beforeSave($insert) { if (parent::beforeSave($insert)) { if ($insert) { if ($this->hasAttribute('created_at')) { $this->created_at = time(); } } if ($this->hasAttribute('updated_at')) { $this->updated_at = time(); } return true; } return false; }
方法二:TimestampBehavior
public function behaviors() { return [ [ 'class' => TimestampBehavior::className(), 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'], ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'], ], 'value' => time(), ], ]; }