《magento企业级开发实战》重磅发布!
全面系统学习magento二次开发,点击链接查看:
《magento企业级开发实战》https://www.kancloud.cn/sbynng1987/magento2_enterprise_develop
Magento 2 具有用于与数据库交互的资源的概念,本教程涵盖了如何获取全局资源以及如何使用任何 SQL 查询并直接执行的技术……
A - 首先你需要在 di.xml 中注入对象资源 Magento\Framework\App\Resource 在这里我将注入到我的控制器 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 - 在我的操作中,我获取资源并将其放入类变量;
protected _resource;
public function __construct(Context $context,
\Magento\Framework\App\ResourceConnection $resource)
{
$this->_resource = $resource;
parent::__construct($context);
}
C – 现在我可以获取用于阅读和写作的流或资源:
$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);
$showTables =$connection->fetchCol('show tables');
D – 一些例子:
获取它连接前缀的表的名称
$tblSalesOrder = $connection->getTableName('sales_order');
获取所有这些使用选择语句:
$result1 = $connection->fetchAll('SELECT quote_id FROM `'.$tblSalesOrder.'` WHERE entity_id='.$orderId);
或自定义查询,您可以使用以下方式进行原始查询:
$connection->rawQuery('DELETE FROM `'.$tblSalesCreditmemoGrid.'` WHERE order_id='.$orderId);