0

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

上面的代码不会抛出任何异常,并且由于验证规则失败而丢失了第四个表的数据。

4

2 回答 2

1

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();
    }
}
于 2012-11-09T01:28:08.577 回答
0

上面代码的第 5 行你有:

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

它应该是

$fourthChild->attributes = $_POST['FourthChild'];
于 2012-11-08T21:10:42.063 回答