[Solved] Saving Model Using Transaction

Hello. I have following code:


$connection=new CDbConnection(......);

$connection->active=true;

$transaction=$connection->beginTransaction();

            

$model=new Post;

$model->name="test";

$model->save();

               

$transaction->rollBack();

But rollback doesn’t work and Post is in database. What should be wrong?

What database are you using? Maybe it doesn’t support transactions. If it’s MySQL, make sure the tables are created using InnoDB engine, not MyISAM.

Oh I just noticed you create an extra connection. AR used the connection defined in ‘db’ component of your application, not just any connection you create. If you want to use a different connection please override the getDbConnection method.

I used same connection, so following code solved the problem:


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

Thanks

Or better:




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



That way, if you ever overload the getDbConnection() method to use other component than the default ‘db’ you won’t have to change your code.