使用单个事务提交和回滚的多个模型的事务管理

Moh*_*qar 5 cakephp transactions cakephp-model

我是cakephp的新手.我想知道在cakephp中是否可以使用单个事务处理多个模型提交和回滚.我想做这样的事情

<?php
function add(){
    $transaction = begintransaction;
    if(model1->save()){
        if(model2->save()){
            if(model3->save(){
            }
            else{
                $errorFlag['model3'] = "Error in model 3"; 
            }
        }
        else{
            $errorFlag['model2'] = "Error in model 2";
        }
    }
    else{
        $errorFlag['model3'] = "Error in model 3";
    }
    if(empty($errorFlag)){ //no error in saving the model
        $transaction->commit();
        $this->Session->setFlash(__('The form data with multiple model is saved', true)); 
    }
    else{   //error in saving the model
        $transaction->rollback();
        $this->Session->setFlash(__('The form data with multiple model is saved', true));
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

ban*_*cer 3

是的你可以。

$this->Model->begin(); // Start transaction
$this->Model->commit(); // Commit transaction
$this->Model->rollback(); // Rollback transaction
Run Code Online (Sandbox Code Playgroud)

还要看看手册