How to get the default core write and read resources in Magento 2
Since Magento 2 relies on the concept of resources to interact with database, you can easily get the global resource and use it for playing with SQL queries or execute directly.

In order to achieve this goal, you have to inject the object resource Magento\Framework\App\Resource inside di.xml.
In the following example, we use a custom action of the MassDelete controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd"> <type name="Ibnab\DeleteOrders\Controller\Adminhtml\Order\MassDelete"> <arguments> <argument name="deleteorderAction" xsi:type="array"> <item name="context" xsi:type="string">Magento\Backend\App\Action\Context</item> <item name="resource" xsi:type="string">Magento\Framework\App\Resource</item> </argument> </arguments> </type> </config> |
Now, get the resource and put it to the class variable inside the action:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
protected _resource; public function __construct(Context $context, \Magento\Framework\App\Resource $resource) { $this->_resource = $resource; parent::__construct($context); } |
Get a stream or resource for reading / writing :
1 2 3 4 5 |
$connectionReader = $this->_resource->getConnection(\Magento\Framework\App\Resource::DEFAULT_READ_RESOURCE); $connectionWriter = $this->_resource->getConnection(\Magento\Framework\App\Resource::DEFAULT_WRITE_RESOURCE); $showTables = $connectionWriter->fetchCol('show tables'); |
Now:
- get the name of a table that concat the prefix
1 |
$tblSalesOrder = $connectionReader->getTableName('sales_order'); |
- fetch a use select statement
1 |
$result1 = $connectionWriter->fetchAll('SELECT quote_id FROM `'.$tblSalesOrder.'` WHERE entity_id='.$orderId); |
or a custom query:
1 |
$connectionWriter->rawQuery('DELETE FROM `'.$tblSalesCreditmemoGrid.'` WHERE order_id='.$orderId); |
More tips from Magento 2 Developer’s Cookbook
