I have copied the following code from other websites and stackoverflow answers (yii2 behaviors ActiveRecord::EVENT_BEFORE_INSERT not working) and can't get it to work:
public function behaviors()
{
return [
'timestamp' => [
'class' => \yii\behaviors\TimestampBehavior::className(),
'attributes' => [
\yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
\yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
'value' => new \yii\db\Expression('NOW()'),
],
];
}
My model's code is:
namespace app\models;
use Yii;
class Setting extends \yii\db\ActiveRecord
{
/*
* Autoupdate created_at and updated_at fields.
*/
public function behaviors()
{
return [
'timestamp' => [
'class' => \yii\behaviors\TimestampBehavior::className(),
'attributes' => [
\yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
\yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
'value' => new \yii\db\Expression('NOW()'),
],
];
}
/**
* @inheritdoc
*/
public static function tableName()
{
return 'settings';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['value'], 'required'],
[['value', 'reference', 'notes'], 'string'],
[['created_at', 'updated_at'], 'safe'],
[['property'], 'string', 'max' => 255]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'property' => 'Property',
'value' => 'Value',
'reference' => 'Reference',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'notes' => 'Notes',
];
}
/**
* Get a property
*/
public static function getSetting($property_name)
{
$setting = self::find()->where(['property' => $property_name])->one();
if(is_null($setting))
return NULL;
else
return $setting->value;
}
}
When I create a new setting, the created_at
and updated_at
column is set to 0000-00-00 00:00:00
but when I then update the row again, updated_at
works. Seems like the EVENT_BEFORE_INSERT isn't executing.
Until a more suitable answer comes along, I achieved it using
beforeSave()
:I have had this exact same problem in MySQL. The issue was that my database column for "created_at" was set as a timestamp datatype. I have found that you need to declare the database column as int(11) for it to work properly.
You can use for time() method in Yii2 via following code: