1

感谢所有 stackoverflow 成员,我从这里学到了很多东西。

我有一个关于“beforeSave”的问题,我想将旧数据保存到数据库中的历史表中,例如,如果用户更改任何我想将旧信息保存在历史表中的内容。

谁能告诉我实现这一目标的“最佳”方案是什么?

谢谢大家,欢迎提出所有建议。

4

2 回答 2

1

您必须在模型中添加 beforSave() 函数。
检查参数 $insert 是否为假,这意味着您正在更新记录,因此在这种情况下,您可以创建一个新的 HistoryModel,填充并保存

  public function beforeSave($insert)
  {
      if(parent::beforeSave($insert))
      {
          if(! $insert)
          {
              $historyModel = new History();
              $historyModel->att1 = $this->att1;
              $historyModel->att2 = $this->att2;
              ......
              $historyModel->attN = $this->attN;
              $historyModel->save();
              return true;
          }

      }

http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#beforeSave%28%29-detail

于 2017-09-04T11:15:35.757 回答
0

对于所有其他只想保存对数据库的更改的人,这里是代码:

  public function afterSave($insert, $changedAttributes) {
    parent::afterSave($insert, $changedAttributes);
    if(!$insert) {
        $historyModel = new History();
        if(isset($changedAttributes['attr1']  )){
            $historyModel->attr1 = $changedAttributes['attr1'];
        }
        ...
        $historyModel->save(false);
    }
}

现在您只能保存对数据库的更改,而不是每次都保存所有记录...

于 2017-09-06T06:53:03.807 回答