请帮我在这个YII交易代码中找到错误

时间:2012-11-08 21:08:12

标签: transactions yii

我有一个庞大的表单,我想将表单保存到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();
    }
}

上面的代码不会因为验证规则失败而丢失第四个表丢失的任何异常和数据。

1 个答案:

答案 0 :(得分:0)

您拥有以上代码的第5行:

$fourthChild-->attributes = $_POST['FourthChild'];

应该是

$fourthChild->attributes = $_POST['FourthChild'];