Transaction management using multiple models using a transaction with transaction commit and rollback

I am new to cakephp. I want to know if cakephp can handle multiple model commits and rollbacks with a single transaction. I want to do something like this

<?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));
    }
}
?>
+5
source share
3 answers

Yes, you can.

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

Also review the manual .

+3
source

If your 1-3 models have a “has many” or “belong” relationship, you should probably use

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

He will take care of checking and saving all published model data in one transaction.

+3

- Model:: saveAll(), .

If you cannot use saveAll (), you need to use something like Model :: query (), you can do:

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

As with Cake 1.3, it really doesn't matter which model you use when you start the begin / commit / rollback statements; all of them cause the execution of the same code and do not have any side effects specific to a particular model.

+1
source

All Articles