Save multiple models at a time in Yii2

最后都变了- 提交于 2020-02-24 04:31:30

问题


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 ?


回答1:


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();
}



回答2:


Yii2 can already do that. Validate the input before save the data to the model:

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
   }
}

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




回答3:


Try to see what errors the Users model returns. Call getErrors() method in the 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 the errors that don't allow to save the Users model.



来源:https://stackoverflow.com/questions/35221212/save-multiple-models-at-a-time-in-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!