Ahmed
Ahmed

Reputation: 651

Magento multiple database transactions in single commit

I know how to do it in zend framework

$db->beginTransaction();

try {
   $db->query(...);
   $db->query(...);
   $db->query(...);
   .
   . 
   .
   $db->commit();
} catch (Exception $e) {
    $db->rollBack();
}

but I want to do it using magento model, something like

$db->beginTransaction();

try {
   $modelOne   = Mage::getModel('modulename/table1');
   $modelTwo   = Mage::getModel('modulename/table2');
   $modelThree = Mage::getModel('modulename/table3');

   $db->query($modelOne);
   $db->query($modelTwo);
   $db->query($modelThree);
   .
   . 
   .
   $db->commit();
} catch (Exception $e) {
    $db->rollBack();
}

If anyone of them failed to save then all should be rolled back

Thanks

Upvotes: 4

Views: 3442

Answers (2)

Elavarasan
Elavarasan

Reputation: 2669

For INSERT , DELETE and UPDATE in a single transaction (as per your comment) try below,

<?php

$id1 = 1; //update id
$id2 = 2; //delete id
$data = array('title'=>'New Title','content'=>'Hello, there..!','status'=>1);
$update = array('title'=>'My title', 'content'=>'Hi, there..!', 'status'=>1); 

try {
    $transaction = Mage::getModel('core/resource_transaction')
                           ->addObject(Mage::getModel('modulename/table1')->load($id1)->addData($update));
                           ->addObject(Mage::getModel('modulename/table2')->setId($id2)->delete());
                           ->addObject(Mage::getModel('modulename/table3')->setData($data));

    $transaction->save();
} catch (Exception $e) {
    echo $e->getMessage();
}

I didn't tested this. Just try by your own risk. The problem is you can't get the last insert id for all db-transaction in this. The delete() doesn't required to call save(). But the INSERT and UPDATE method you need to call the save() finally. Please update the result is it working or not.

Upvotes: 1

ToxaBes
ToxaBes

Reputation: 1587

Look at app/code/core/Mage/Core/Model/Resource/Transaction.php

This model allow to add another Models as objects in transaction. During save it call $object->save() for each added object. If something fails, it call $object->getResource()->rollBack() for each object. You also can add commit callbacks via addCommitCallback(array($object, 'callbackFunctionName')).

If you need delete transaction, call $transaction->delete() instead of $transaction->save() In this case it call $object->delete() instead of $object->save() for each object.

Example:

try {
    $transaction = Mage::getModel('core/resource_transaction')
                           ->addObject(Mage::getModel('modulename/table1'))
                           ->addObject(Mage::getModel('modulename/table2'))
                           ->addObject(Mage::getModel('modulename/table3'));

    $transaction->save();
} catch (Exception $e) {
    echo $e->getMessage();
}

Upvotes: 5

Related Questions