Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transaction management with multiple models using single transaction commit and rollback

I am new to cakephp. I want to know if it is possible in cakephp to to handle multiple model commit and rollback with single transaction. I want to do some thing 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));
    }
}
?>
like image 706
Mohd Viqar Avatar asked Jun 10 '10 09:06

Mohd Viqar


2 Answers

If your models 1-3 have "has many" or "belongs to" relationships, you should probably use

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

It will take care of validating and saving all posted model-data in a single transaction.

like image 195
geon Avatar answered Sep 20 '22 16:09

geon


Yes, you can.

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

Also take a look at the manual.

like image 41
bancer Avatar answered Sep 18 '22 16:09

bancer