【发布时间】:2017-07-18 06:48:51
【问题描述】:
我已经花了很多时间,但我还不知道问题出在哪里。
我正在尝试实现TimeStampBehaviour(和Blamable,但它们现在都没有工作)。我的模型课:
<?php
namespace common\models;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
use yii\db\ActiveRecord;
/**
* This is the model class for table "news".
* .... property list
*/
class News extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'news';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['title', 'short_description', 'content'], 'required'],
[['content'], 'string'],
[['title'], 'string', 'max' => 128],
[['short_description'], 'string', 'max' => 255],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
// ... attribute label list
}
public function behaviors()
{
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
'value' => new Expression('NOW()'),
],
'blameable' => [
'class' => BlameableBehavior::className(),
'createdByAttribute' => 'created_by',
'updatedByAttribute' => 'updated_by',
],
];
}
}
我可以保存我的模型,每个字段都已正确更新,但 created_at、updated_at、created_by、updated_by 字段始终为空。
我的数据库表名是 news,它包含 4 个字段:created_at 和 updated_at 字段的类型是 DATETIME(我已经尝试过使用 INT 和 UNIX 时间戳,但它不起作用),其他的类型是整数。
可能是什么问题?我已经尝试了与我的朋友 Google 一起找到的所有内容。 :) 谢谢。
更新 #1:
我的 NewsController 的创建和更新操作:
public function actionCreate()
{
$model = new News;
if ($model->load(Yii::$app->request->post()))
{
if($model->save()) {
$this->redirect(array('index'));
}
}
return $this->render('create',array(
'model'=>$model,
));
}
public function actionUpdate($id)
{
$model = $this -> findModel ($id);
if ($model->load(Yii::$app->request->post())) {
if($model->save()) {
$this->redirect(array('index'));
}
}
return $this->render('update',array(
'model'=>$model,
));
}
更新 #2: 我“不小心”注意到,如果我尝试更新我的模型,问题就存在。我刚刚创建了一个新模型,并且所有四列都填充了正确的数据。
更新 #3:
protected function findModel($id)
{
if (($model = News::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
【问题讨论】:
-
您能否使用负责保存此模型的操作代码更新您的问题?
-
findModel的代码是什么? -
您说
news表仅包含 4 个字段,但您的规则中有 3 个不同的字段用于此模型。它是否有效? -
对不起,我不知道为什么这不起作用。更新模型时,您是否更改了任何字段?如果您只是单击保存而不进行任何更改,它将不会更新数据库。
-
你不会相信,但我刚刚找到了相同的解决方案。 :( 对不起我的菜鸟错误,我以为每次调用更新方法都会更新。非常感谢您的帮助!
标签: yii2 yii2-advanced-app yii2-model yii-behaviour