Control transaction on two or more models at same time

Hi,

I have two or more models that is inserted on database at the same time, but i need control transaction because if any one of this models get error, the transaction rollback all operations.

Example:


[start transaction]


try


    $model1 = new Product;

    $model1->save();


    $model2 = new ProductImage;

    $model2->save();


    $model3 = new ProductImage;

    $model3->save();


    [commit transaction]


catch

   

    [rollback all transactions]



So, how i can do it with Yii? The Yii tutorial only teach how to control transaction over one model, but i have 3 save called in differente models.

All of your models use the same connection so this should work




$transaction = Yii::app()->db->beginTransaction();

...

$transaction->commit();

...

$transaction->rollback();



/Tommy

I use it like this.

You will need to change the code below according to your needs.




$model1 = new Product;

$model2 = new ProductImage;

$model3 = new ProductImage;


$transaction = $this->dbConnection->beginTransaction();

try {

    if (!$model1->save()) {

            $transaction->rollback();

            return false;

    }

    

    if (!$model2->save()) {

            $transaction->rollback();

            return false;

    }

    

    if (!$model3->save()) {

            $transaction->rollback();

            return false;

    }


    $transaction->commit();

} catch (Exception $ex) {

    $transaction->rollback();

    return false;



(Bump)

This is good to know :)

But where do you put this script? As I understand it correctly (I’m still a newbie…) database actions belong in a model. But here we have multiple queries over multiple models. It does not belong to one model so it cannot be in one model, right? I was thinking about a component which handles the transaction. What should be good practice?

Greetings!