Answer the question
In order to leave comments, you need to log in
Yii2AR. What is the correct way to create 50 models in the afterSave event of another model?
Hello! In AR, there are afterSave events that fire after the model record is saved. I need to generate approximately 50 records of another model in this event and store them in the corresponding table.
class Reservation extends \yii\db\ActiveRecord
public function afterSave($insert, $changedAttributes)
{
if (parent::afterSave($insert, $changedAttributes)) {
for ($i=0; $i < 50; $i++) {
$modelRegCleanings = new RegularCleanings();
$modelRegCleanings->id_reservation = $this->id_reservation;
$modelRegCleanings->notes = $changedAttributes['notes'];
$modelRegCleanings->save();
}
return true;
} else {
return false;
}
}
public function actionCreate()
{
$model = new Reservation();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id_reservation]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Answer the question
In order to leave comments, you need to log in
I have no idea why you need to create 50 entries... oh my. Do where you want. True, for good, I would generally do it all in the service that would control this logic. Well, or would take out the generation in a static method of the target model ... everything depends on the business logic.
Concerning the notification - flash messages.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question