Setting unknown property: common\models\User::created_at timestamp

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:

  1. public function behaviors()
  2. {
  3.     return [
  4.         TimestampBehavior::className(),
  5.     ];
  6. }

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:

  1. public function behaviors()
  2. {
  3.     return [
  4.         'timestamp' => [
  5.             'class' => '\yii\behaviors\TimestampBehavior',
  6.             'attributes' => [
  7.                 ActiveRecord::EVENT_BEFORE_INSERT => ['date_created', 'date_updated'],
  8.                 ActiveRecord::EVENT_BEFORE_UPDATE => ['date_updated'],
  9.             ],
  10.             'value' => new \yii\db\Expression('NOW()'),
  11.         ],
  12.     ];
  13. }

Setting the value property to new \yii\db\Expression(‘NOW()’) will create sql such as date_created = NOW().

Published by

Joel Bowers

Web developer since 1999. PHP, YII2, Laravel, Javascript, HTML, CSS, jQuery, Perl, Wordpress, MySQL.

Leave a Reply

Your email address will not be published. Required fields are marked *