【问题标题】:Yii set model attributes and saveYii 设置模型属性并保存
【发布时间】:2017-04-28 11:36:30
【问题描述】:

我想跟踪我的表中的更改并将其保存在另一个表中。例如,如果有人编辑我的“文本”表,我将其保存在“文本更改”表中。我的 textchanges 有 4 列,id、textid(外键)、旧文本、更改日期。我正在尝试做什么,在我的文本控制器中接近动作更新时,我创建了新的 textchange 模型并设置了属性,但它不起作用。

public function actionUpdate($id)
{
    $model = $this->loadModel($id);

        if (isset($_POST['Text'])) {
            $model->attributes = $_POST['Text'];

            $textChange = new TextsChanges();
            $textChange->setAttributes(array('TextId' => $model->text_id, 'TextBefore' => $model->text_text, 'ChangeDate' => new DateTime()));

            if ($model->save())
                $this->redirect(array('view', 'id' => $model->text_id));
                $textChange->save();
        }

        $this->render('update', array(
            'model' => $model,
        ));
}

【问题讨论】:

    标签: php database yii


    【解决方案1】:

    您应该在分配给模型之前分配旧值,如下所示。

    public function actionUpdate($id)
    {
        $model = $this->loadModel($id);
    
            if (isset($_POST['Text'])) {
                $textChange = new TextsChanges();
                $textChange->setAttributes(array('TextId' => $model->text_id, 'TextBefore' => $model->text_text, 'ChangeDate' => new DateTime()));
    
                $model->attributes = $_POST['Text'];
    
                if ($model->save())
                    $this->redirect(array('view', 'id' => $model->text_id));
                    $textChange->save();
            }
    
            $this->render('update', array(
                'model' => $model,
            ));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多