Yii2时间戳行为正在恢复0000-00-00 00:00:00 [英] Yii2 Timestamp Behavior is returning 0000-00-00 00:00:00
问题描述
我已经复制从其他网站下面的code和StackOverflow的答案(<一href="http://stackoverflow.com/questions/27085990/yii2-behaviors-activerecordevent-before-insert-not-working?rq=1">yii2行为的ActiveRecord :: EVENT_BEFORE_INSERT不工作),并不能得到它的工作:
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()'),
],
];
}
我的模型code是:
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;
}
}
当我创建一个新的设置, created_at
和的updated_at
列设置为 0000-00-00 00:00:00
但是当我再一次更新该行,的updated_at
的作品。好像EVENT_BEFORE_INSERT没有执行。
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.
推荐答案
直到一个更合适的答案出现时,我使用做到了这一点 beforeSave()
:
Until a more suitable answer comes along, I achieved it using beforeSave()
:
/*
* Autoupdate created_at and updated_at fields.
*/
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if($insert)
$this->created_at = date('Y-m-d H:i:s');
$this->updated_at = date('Y-m-d H:i:s');
return true;
} else {
return false;
}
}
这篇关于Yii2时间戳行为正在恢复0000-00-00 00:00:00的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!