After saving, yii2 will call the aftersave method. Aftersave only does one thing, which is to trigger the corresponding event event, EVENT_AFTER_INSERT or EVENT_AFTER_UPDATE. You can look at the events of Yii2
It is necessary to save the data submitted by the user to the look table, and at the same time, the add_img image address array in the form is saved to the lookmeida table respectively. (Recommended learning:yii tutorial)
This extra function of saving pictures does not need to change the controller code. With the help of the Model's afterSave life cycle function, it can automatically help us Finish. The principle is that after the record in the look table is saved (or modified), a lookid will be generated, and then we will store this lookid and mediaurl in the lookmedia table.
public function afterSave($insert,$changedAttributes) { if (Yii::$app->id=='app-backend'){ //保存图片字段 $add_imgarr=$this->add_img; if ($add_imgarr){ foreach (array_filter($add_imgarr) as $mediaurl){ $lookmedia=new Lookmedia(); $lookmedia->lookid=$this->lookid; $lookmedia->mediaurl=$mediaurl; $lookmedia->type=0; $lookmedia->save(); } } } if (parent::afterSave($insert,$changedAttributes)) { return true; }else return false; }
I only mention three points here, which can be regarded as a few pitfalls:
1) The parameters of afterSave, $insert and $changedAttributes are fixed writing methods and must be present, otherwise an error will be reported .
2) Inside the function, in the local environment, what I wrote before was beforeSave, no error was reported, and the program ran normally; but after transplanting to the server, an error was reported, so it was changed to afterSave and then it was normal.
3) According to actual measurement, our new logic must be placed outside the parent function, otherwise it will not be executed (the picture has been uploaded, but there is no record in the lookmedia table)
The above is the detailed content of How to use yii2 aftersave. For more information, please follow other related articles on the PHP Chinese website!