Transaction management with multiple models using single transaction commit and rollback
Asked Answered
S

3

6

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));
    }
}
?>
Sherysherye answered 10/6, 2010 at 9:57 Comment(0)
U
3

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.

Usage answered 10/6, 2010 at 23:51 Comment(2)
This one doesn't work. Undefined property: MyController::$Model Do you mean Model - is just some of the model classes defined for controller? If so - are other views included in such transaction?Dippy
Change "Model" to your model class name. I did not understand your question about views. If you have a specific problem open a new question.Usage
P
3

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.

Psychotherapy answered 15/3, 2011 at 15:35 Comment(0)
M
2

The most preferable method is Model::saveAll(), if they are related.

If you can't use saveAll() becuase you need to use something such as Model::query(), you can do:

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

As of Cake 1.3, it doesn't actually matter what model you're using when you run the begin/commit/rollback statements; they all cause the same code to execute and don't have any model-specific side effects.

Markson answered 30/8, 2011 at 1:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.