Magento 2 Programming : Get default core write and read resource (row direct sql)
Magento 2 have concept of resource yes for interact wih database , this tutorial cover the technique of how getting the global resource and using for play with any SQL query and execute directly …
A – Fist you need inject the object resource Magento\Framework\App\Resource inside di.xml here I will inject to my custom action of controller MassDelete ...
<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\ResourceConnection</item> </argument> </arguments> </type> </config>
B - inside of My action I get the resource and I put to class variable ;
protected _resource; public function __construct(Context $context, \Magento\Framework\App\ResourceConnection $resource) { $this->_resource = $resource; parent::__construct($context); }
C – now I can get my stream or resource for reading and writing :
$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION); $showTables =$connection->fetchCol('show tables');
D – Some example :
get the name of table it concat the prefix
$tblSalesOrder = $connection->getTableName('sales_order');
fetch all this use select statement :
$result1 = $connection->fetchAll('SELECT quote_id FROM `'.$tblSalesOrder.'` WHERE entity_id='.$orderId);
or custom query you can raw query with :
$connection->rawQuery('DELETE FROM `'.$tblSalesCreditmemoGrid.'` WHERE order_id='.$orderId);
Comments