【问题标题】:Transaction management with multiple models using single transaction commit and rollback使用单个事务提交和回滚的多个模型的事务管理
【发布时间】:2010-06-10 09:57:21
【问题描述】:

我是 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));
    }
}
?>

【问题讨论】:

    标签: cakephp transactions cakephp-model


    【解决方案1】:

    如果您的模型 1-3 具有“有很多”或“属于”关系,您可能应该使用

    $this->Model1->saveAll($this->data);
    

    它将负责在单个事务中验证和保存所有已发布的模型数据。

    【讨论】:

      【解决方案2】:

      是的,你可以。

      $this->Model->begin(); // Start transaction
      $this->Model->commit(); // Commit transaction
      $this->Model->rollback(); // Rollback transaction
      

      还可以看看manual。

      【讨论】:

      • 这个不行。未定义的属性:MyController::$Model 你的意思是 Model - 只是为控制器定义的一些模型类吗?如果是这样 - 此类交易中是否包含其他视图?
      • 将“模型”更改为您的模型类名称。我不明白你关于观点的问题。如果您有特定问题,请打开一个新问题。
      【解决方案3】:

      最好的方法是 Model::saveAll(),如果它们是相关的。

      如果你不能使用 saveAll() 因为你需要使用 Model::query() 之类的东西,你可以这样做:

      $this->ModelX->begin();
      $this->Model1->query();
      $this->Model2->query();
      $this->ModelX->commit();
      

      从 Cake 1.3 开始,运行 begin/commit/rollback 语句时使用的模型实际上并不重要;它们都导致执行相同的代码,并且没有任何特定于模型的副作用。

      【讨论】:

        猜你喜欢
        • 2014-05-18
        • 1970-01-01
        • 2016-06-23
        • 1970-01-01
        • 2012-12-24
        • 2013-11-22
        • 1970-01-01
        • 1970-01-01
        • 2011-12-10
        相关资源
        最近更新 更多