Save multiple models at a time in Yii2

I have two models: Usersand Students. I want to insert data into these tables at the same time. First, I save the data in the model Students, and then in the models Users.

Now, if the data is not successfully inserted into the model Users, there is already a record in the table Students. What I want is data records in both models, only if the data can be successfully stored in both.

Now my controller code looks something like this:

    public function actionCreate()
        {
            $model = new Students();
            $userModel = new Users();    
if ($model->load(Yii::$app->request->post()) && $userModel->load(Yii::$app->request->post()) && $model->save() && $userModel->save()) 
        {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'userModel' => $userModel,
            ]);
        }
    }

there is an error in the user model and does not return true when I call $userModel->save(). here $userModel->save()returns true and inserts data into the table.

Is there any other way to do this without any complications?

+4
3

, . :

$transaction = Yii::$app->db->beginTransaction();

try  {
    if ($model->save() && $userModel->save()) {
        $transaction->commit();
    } else {
        $transaction->rollBack();
    }
} catch (Exception $e) {
    $transaction->rollBack();
}
+10

Yii2 . :

if ( $model->load(Yii::$app->request->post() && $userModel->load(Yii::$app->request->post() ) {

   // Check validation
   if ($model->validate() && $userModel->validate()) {
       $model->save();
       $userModel->save();

   } else {
       // Throw error
   }
}

: http://www.yiiframework.com/doc-2.0/guide-input-validation.html

+1

Try to see what errors the Users model returns. Call getErrors () method on else condition.

if ($model->load(Yii::$app->request->post()) && $userModel->load(Yii::$app->request->post()) && $model->save() && $userModel->save()) 
{
    return $this->redirect(['view', 'id' => $model->id]);
} else {
    var_dump($userModel->getErrors());
    ....
}

And you will see errors that prevent the Users model from being saved.

0
source

Source: https://habr.com/ru/post/1627416/


All Articles