在 Yii2 中一次保存多个模型 [英] Save multiple models at a time in Yii2

查看:30
本文介绍了在 Yii2 中一次保存多个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,UsersStudents.我想同时将数据插入这些表中.首先,我将数据保存到 Students 模型中,然后保存到 Users 模型中.

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.

现在,如果数据没有成功插入到 Users 模型中,那么 Students 表中已经有一个条目.我想要的是只有在数据可以成功保存在两个模型中的情况下才能将数据输入到两个模型中.

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,
            ]);
        }
    }

用户模型中有错误,当我调用 $userModel->save() 时没有返回 true.在这里,$userModel->save() 返回 true 并将数据插入到表中.

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 ?

推荐答案

您应该使用事务来确保正确保存两个模型.示例:

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

这篇关于在 Yii2 中一次保存多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆