【发布时间】:2015-06-27 11:24:25
【问题描述】:
我从其他网站和 stackoverflow 答案 (yii2 behaviors ActiveRecord::EVENT_BEFORE_INSERT not working) 复制了以下代码,但无法正常工作:
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 没有执行。
【问题讨论】:
-
列的数据类型是什么?
-
时间戳,所以 yyyy-mm-dd hh:mm:ss
-
用
CURRENT_TIMESTAMP()函数检查。
标签: php activerecord yii2 behavior