/   /   /  Magento 2 Programming : Get default core write and read resource (row direct sql)

Note:

For more extensions and themes visit our store

Magento 2 Programming : Get default core write and read resource (row direct sql)


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 ...

  1.  
  2. <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">  
  3.     <type name="Ibnab\DeleteOrders\Controller\Adminhtml\Order\MassDelete">
  4.         <arguments>
  5.             <argument name="deleteorderAction" xsi:type="array">
  6.                 <item name="context" xsi:type="string">Magento\Backend\App\Action\Context</item>
  7.                 <item name="resource" xsi:type="string">Magento\Framework\App\ResourceConnection</item>
  8.             </argument>
  9.         </arguments>
  10.     </type>
  11. </config>
  12.  

B - inside of My action  I get the resource and I put to class variable ;

  1.  
  2.   protected  _resource;
  3.   public function __construct(Context $context,
  4. \Magento\Framework\App\ResourceConnection $resource)
  5.   {
  6.     $this->_resource = $resource;
  7.     parent::__construct($context);
  8.  
  9.   }
  10.  

C – now I can get my stream or resource for reading and writing :
  1.  
  2. $connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);
  3.         $showTables =$connection->fetchCol('show tables');
  4.  

D – Some example :

get the name of table it concat the prefix

  1.  
  2. $tblSalesOrder = $connection->getTableName('sales_order');
  3.  

fetch all this use select statement :
  1.  
  2. $result1 = $connection->fetchAll('SELECT quote_id FROM `'.$tblSalesOrder.'` WHERE entity_id='.$orderId);
  3.  


or custom query you can raw query with :

  1.  
  2. $connection->rawQuery('DELETE FROM `'.$tblSalesCreditmemoGrid.'` WHERE order_id='.$orderId);
  3.  

Comments

Related Posts

make your store more efficient

Solving problems. With open source technology. Professional results. That’s what makes Ibnab your best choice

IBNAB is a company made of a group of professionals whose work is providing secure open source solutions. Our company strives for reaching magnificent results with each experience and provides professional open source solutions that cover every part of the business process.