Magento single-user multi-user transactions

I know how to do this in the zend framework

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

but I want to do this using the 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 one of them could not save, everyone should be thrown back

thanks

+4
source share
2 answers

Take a look at application / code / kernel /Mage/Core/Model/Resource/Transaction.php

This model allows you to add other models as objects in a transaction. During saving, call $object->save() for each added object. If something fails, it calls $object->getResource()->rollBack() for each object. You can also add commit callbacks via addCommitCallback(array($object, 'callbackFunctionName')) .

If you need to delete a transaction, call $transaction->delete() instead of $transaction->save() . In this case, instead of $object->save() $object->delete() is called to call the object $object->delete() .

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(); } 
+5
source

For INSERT, DELETE and UPDATE in one 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 have not tested this. Just try at your own risk. The problem is that you cannot get the last insert id for all db transactions. delete() not required to call save() . But the INSERT and UPDATE method you need to finally call save() . Please update the result, it works or not.

+1
source

Source: https://habr.com/ru/post/1209223/


All Articles