当前位置: 技术文章>> 如何在Magento 2中使用标准方式编写删除SQL查询而不使用模型文件

文章标题:如何在Magento 2中使用标准方式编写删除SQL查询而不使用模型文件
  • 文章分类: Magento
  • 17537 阅读
系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》

本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。


这是我执行删除SQL查询以向您展示一个演示,该演示如何在不使用Magento 2中的模型文件的情况下删除特定数量的行/记录。

为此,我使用以下代码在此路径的扩展文件夹中创建了“Index.php”文件。

app\code\Vendor\Extension\Controller\Deletequery\

<pre class="lang:default decode:true">
<?php
namespace Vendor\Extension\Controller\Deletequery;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\App\Action\Context;
class Index extends \Magento\Framework\App\Action\Action
{
 const QUOTE_TABLE = 'quote';
 private $resourceConnection;
 public function __construct(
     Context $context,
     ResourceConnection $resourceConnection)
 {
     $this->resourceConnection = $resourceConnection;
     return parent::__construct($context);
 }
 public function execute()
 {
     $connection  = $this->resourceConnection->getConnection();
     $tableName = $connection->getTableName(self::QUOTE_TABLE);
     $quoteId = 191;
     $whereConditions = [
            $connection->quoteInto('entity_id = ?', $quoteId),
     ];
     $deleteRows = $connection->delete($tableName, $whereConditions);
    echo "Deleted Rows : ".$deleteRows;
 }
}
</pre>

就是这样。使用此代码,您可以执行类似的不同SQL操作,而无需创建标准的Magento 2模型文件。


推荐文章