[英]Yii2 Timestamp Behavior is returning 0000-00-00 00:00:00
我已經從其他網站復制了以下代碼,並獲得了stackoverflow的答案( yii2行為ActiveRecord :: EVENT_BEFORE_INSERT無法正常工作 ),並且無法正常工作:
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()'),
],
];
}
我模型的代碼是:
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沒有執行。
在找到更合適的答案之前,我使用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;
}
}
我在MySQL中有這個完全相同的問題。 問題是我的“ created_at”數據庫列設置為時間戳數據類型。 我發現您需要將數據庫列聲明為int(11)才能正常工作。
您可以通過以下代碼在Yii2中使用time()方法:
Yii::$app->formatter->asTimestamp(date('Y-d-m h:i:s'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.