Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save multiple models at a time in Yii2

I have two models, Users and Students. I want to insert data into these tables simultaneously. First, I save data into Students model and then into Users models.

Now, if data doesn't successfully get inserted into Users model there is already an entry into Students table. What I want is data entries into both model only if data can be successfully saved 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 users model and not return true when i call $userModel->save() . here, $userModel->save() return true and inserts data to the table.

Is there any other option to do this without any complication ?

like image 521
Albert Avatar asked Feb 05 '16 10:02

Albert


1 Answers

You should use transactions to ensure both models are saved correctly. Example:

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

try  {
    if ($model->save() && $userModel->save()) {
        $transaction->commit();
    } else {
        $transaction->rollBack();
    }
} catch (Exception $e) {
    $transaction->rollBack();
}
like image 190
xCrZx Avatar answered Sep 23 '22 06:09

xCrZx