我有两个模型,Users
and Students
。我想同时将数据插入到这些表中。首先,我将数据保存到Students
模型,然后进入Users
楷模。
现在,如果数据没有成功插入到Users
模型已经有一个条目Students
桌子。我想要的是仅当数据可以成功保存在两个模型中时才将数据输入到两个模型中。
Now my 控制器代码看起来像这样:
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,
]);
}
}
用户模型中有错误,当我调用时不返回 true$userModel->save()
。这里,$userModel->save()
返回 true 并向表中插入数据。
有没有其他选择可以做到这一点而不产生任何并发症?
您应该使用事务来确保两个模型都正确保存。例子:
$transaction = Yii::$app->db->beginTransaction();
try {
if ($model->save() && $userModel->save()) {
$transaction->commit();
} else {
$transaction->rollBack();
}
} catch (Exception $e) {
$transaction->rollBack();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)