Yii2 how to save old informations to history-table?

843 views Asked by At

thanks for all stackoverflow members, I learned a lot from here.

I have a question about "beforeSave", I want save the old data to history-table in the database, for example if the user change anything I want save the old informations in the history-table.

Can anyone tell me what's the "best" scenario to achieve this ?

Thank you all and all suggestions are welcome.

2

There are 2 answers

4
ScaisEdge On BEST ANSWER

You must add the beforSave() function in your model.
Check if the param $insert is false theis mean you are updateing a record so in this case you can create a new HistoryModel, polutate and save

  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

0
Andy On

For all others who want save only changes to Database here is the code:

  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);
    }
}

Now you can save only the changes to database and not all records every time...