我有一个巨大的表格,我想将我的表格保存到5个不同的表格,我想确保数据保存到所有5个表中,为此,我试图使用yii过渡但对我不起作用,请查看以下代码以找出错误。
$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();
}
}
上面的代码不会抛出因验证规则故障而丢失的第四个表的任何异常和数据。
yii保存到型号时不会引发异常。
保存后您需要添加自己的错误检查,可能是这样(未经测试):
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
$results = array()
$results[] = $firstChild->save();
$results[] = $secondChild->save();
$results[] = $thirdChild->save();
$results[] = $fourthChild->save(); // fourth child is not saved here, transction should throw exception
foreach($results as $result) {
if (!$result) { throw new Exception('error') }
}
$transaction->commit(); // committing
$this->redirect(array('view','id'=>$ParentModel->id)); // Redirecting on user creation
}
catch (Exception $e){
$transaction->rollBack();
}
}
上述代码的第5行:
$fourthChild-->attributes = $_POST['FourthChild'];
应该是
$fourthChild->attributes = $_POST['FourthChild'];