我有一个巨大的表格,我想将我的表格保存到 5 个不同的表中,我想确保数据保存到所有 5 个表中,为此我正在尝试使用 Yii Transations 但它对我不起作用,请有一个查看下面的代码以找出错误。
$ParentModel->attributes = $_POST['ParentModel'];
$firstChild->attributes = $_POST['FirstChild'];
$secondChild->attributes = $_POST['SecondChild'];
$thirdChild->attributes = $_POST['ThirdChild'];
$fourthChild->attributes = $_POST['FourthChild'];
if($ParentModel->validate())
{
$transaction = $ParentModel->dbConnection->beginTransaction(); // Transaction begin
try{
$ParentModel->save(); // saving parent model
//parent_id is required for all models
$firstChild->parent_id = $ParentModel->id;
$secondChild->parent_id = $ParentModel->id;
$thirdChild->parent_id = $ParentModel->id;
//$fourthChild->parent_id = $ParentModel->id; I commented this line so that fourth child throw an exception on $fourthChild->save() becuase parent_id is required
$firstChild->save();
$secondChild->save();
$thirdChild->save();
$fourthChild->save(); // fourth child is not saved here, transction should throw exception
$transaction->commit(); // committing
$this->redirect(array('view','id'=>$ParentModel->id)); // Redirecting on user creation
}
catch (Exception $e){
$transaction->rollBack();
}
}
上面的代码不会抛出任何异常,并且由于验证规则失败而丢失了第四个表的数据。