transactions

Hi,

can I create a db transaciton that has both active record and database access objects queries?

for example, below, notice how I use both active record and database access objects to perform mysql queries.

I used both active Record save() and also createCommand()->execute()…

How do I do that?




$model=Post::model();

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

try

{

    // find and save are two steps which may be intervened by another request

    // we therefore use a transaction to ensure consistency and integrity

    $post=$model->findByPk(10);

    $post->title='new post title';

    $post->save();




   $transaction->createCommand()->execute();




    $transaction->commit();

}

catch(Exception $e)

{

    $transaction->rollBack();

}

Not tested, but I think you just need to modify your code like this




  ...

  $transaction->getConnection()->createCommand()->execute();

  ...



/Tommy

Let’s say I want to save to different models. I want to save to the Comment model and the Post model, can I use different active record model classes in this transaction also?

like

$model1 = Post::model()->findPk(1);

$model2 = Comment::model()->findPk(1);

As far as I know this should be fine unless you overrode getDbConnection() in any of the involved AR classes, specifying a different CDbConnection component.

/Tommy