Transaction with AR

Hi. I am wondering is it possible to save 10 model objects in the same transaction with AR

I saw from tutorial that for AR i need to get connection from model:


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

But i have 10 model objects from 10 different Model class so each time it gets different connection.

How can I accomplish my aim using AR and same transaction for all models.

thanks in advance.

Usually all AR models should share a single db connection that is defined in config/main.php.




	'db'=>array(

		'connectionString' => 'mysql:host=localhost;dbname=xxxx',

		...



So you can do like this:




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

try

{

    $model->save();

    $model_b->save();

    $model_c->save();

    ...

    $transaction->commit();

}

catch (Exception $e)

{

    $transaction->rollback();

}



I am not sure it will work correctly or not.

Here you are opening one connection with one model then save another object, yii will open another connection for another object so connections are different and they can not be in the same transaction. DO you know how to save model object using the same transaction? Or I am wrong with 1st statement.

You could have easily tested it yourself:




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

try

{

    $model->save();

    $model_b->save();

    $model_c->delete();

    throw new Exception('Error !!'); // add to check if rollback will happen

    $transaction->commit();

}

catch (Exception $e)

{

    $transaction->rollback();

}



If you haven’t overridden getDbConnection() method in a CActiveRecord derived class, it will use ‘db’ application component as the database connection for it by default.

In fact, "Yii::app()->db" equals "$model->dbConnection" in most of the case.

CActiveRecord::getDbConnection() method

The very first instance of AR will actually open the db connection through Yii::app()->db, but once the app component has opened the connection, it will be shared by other instances of AR, not only of the same model but of all the AR models.

If the db connection should have been opened and closed every time a single AR object is created and saved, then transaction would be virtually impossible … but fortunately it’s not the case.

so? how to use transaction between serverl model(different database) in one http request?

It depends on what does "different database" mean. Multiple schemas on the same MySQL server and the same database user can access all of them?