Yii2 models have a nifty feature related to timestamps. When you create a record or update a record, a timestamp is automatically generated and saved to the field created_at and updated_at respectively.
This is accomplished by adding the following to your model:
- public function behaviors()
- {
- return [
- TimestampBehavior::className(),
- ];
- }
However, what if you do not have a created_at field in your table? Or, you have a timestamp field named something else, like date_created?
When you install Yii2 using advanced template, the code above is by default included in the User.php model. If you try to add a user, but you don’t have a created_at field in your user table, you will get the following error:
Setting unknown property: common\models\User::created_at
Fortunately, you can modify this behavior and specify a different field name. Here is the code to specify using date_created and date_updated:
- public function behaviors()
- {
- return [
- 'timestamp' => [
- 'class' => '\yii\behaviors\TimestampBehavior',
- 'attributes' => [
- ActiveRecord::EVENT_BEFORE_INSERT => ['date_created', 'date_updated'],
- ActiveRecord::EVENT_BEFORE_UPDATE => ['date_updated'],
- ],
- 'value' => new \yii\db\Expression('NOW()'),
- ],
- ];
- }
Setting the value property to new \yii\db\Expression(‘NOW()’) will create sql such as date_created = NOW().