Search code examples
yii2yii2-advanced-appyii2-basic-appyii2-modelyii2-validation

Yii2 how to save old informations to history-table?


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.


Solution

  • 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