Magento 2: The way of using SQL transaction for low level operation

The way to guard unit operation of insert or update data in multiple tables and rollback if there is any error in the process

Posted on August 17, 2017 in Magento2

Magento 1:

The following code is used to perform Database Transaction so that the operation of some SQL query will be considered as unit. If there is any error occurred during these commands, the whole process will be rollback.


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

try{
    $connection->beginTransaction();

    //Make save actions

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

Magento 2:


<?php
namespace Jeff\Lib\Helper;

use Magento\Framework\App\ResourceConnection;

class DbConnection {
    protected $_resource;
    protected $_dbConnection;

    protected function __construct(ResourceConnection $resource) {
        $this->_resource = $resource;
        $this->_dbConnection = $this->_resource->getConnection();
    }

    public function Transaction() {
        try{
            $this->_dbConnection->beginTransaction();

            //some save actions

            $this->_dbConnection->commit();
        }
        catch(\Exception $e) {
            $this->_dbConnection->rollBack();
        }
    }
}

I hope these code snippet will help you in your future project when you update or insert data into multiple tables as Unit Operation.


comments powered by Disqus