1

我已经花了很多时间,但我还无法弄清楚问题所在。我正在尝试实现一个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_atupdated_at类型是DATETIME(我已经尝试过使用INT和UNIX时间戳,但它不起作用),其他类型是INTEGER。

可能是什么问题呢 ?我已经尝试了与我的朋友 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.');
    }
}

News表结构: 新闻表结构

4

1 回答 1

1

确保您实际上更改了模型字段中的任何内容,因为如果您只是单击“保存”按钮而不进行任何更改,则模型不会在数据库中更新(没有必要)并且因此 TimestampBehavior 不起作用。

于 2017-07-18T08:59:06.177 回答