Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento Database Transaction

IN Magento How can I insert data in multiple tables in a single transaction and rollback if there is any error in the process.?? I can write custom queries and use transactions but I would prefer if I can do it using Magento methods.

like image 677
sushantsahay Avatar asked Sep 02 '11 11:09

sushantsahay


People also ask

What are Magento 2 transactions?

To ensure the consistency of data, magento2 uses database transactions. Whenever we save a model in Magento, it gets executed as a transaction, when you will dig deeper and check the Magento\Framework\Model\AbstractModel class you will found the save function: public function save()

What is transaction in Magento?

March 2019. In Magento 2 you can use transaction to save objects. This is a less known feature that is helpful, if you want to guarantee a valid state in your database. You can combine many objects to save with a single transaction. This transaction commits or can be rolled back if an error happened.

How do I access database in Magento?

Access my Magento database: So there are three ways to access database: Login in cPanel and clieck on phpmyadmin to access DB. Ask Host for Database direct URL and use your DB username, password to access DB. download third party software like mysql workbench to access DB.

What database does Magento use?

Magento uses MySQL database triggers to improve database access during reindexing. These get created when the indexer mode is set to schedule. Magento does not support any custom triggers in the Magento database because custom triggers can introduce incompatibilities with future Magento versions.


1 Answers

The accepted answer is fine if what you are attempting to do is model saves. This will let you chain any number together with rollback.

If, however, you are performing other actions that might trigger roll-back or are rolling back themselves, then you want to use something more low-level:

$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
try {
    $connection->beginTransaction();

    // Make saves and other actions that affect the database

    $connection->commit();
} catch (Exception $e) {
    $connection->rollback();
}

You can also get the connection from a model, but there may not be one available.

like image 140
Robert Egginton Avatar answered Dec 07 '22 13:12

Robert Egginton