Howdy Devs,
For any CMS, interacting with MYSQL to fetch and retrieve data from the database is like a dependable bond where one needs another to work flawlessly. If you see the Magento 2 which is one of the most used Ecommerce CMS, it also uses MYSQL where it stores different store information like order data, customer details, etc. Many times it happens that being a developer you need to perform some database operations whether it is storing, restriving or deleting records from the database while coding.
According to Magento coding standards, one must create a Model file to perform SQL operations but what if you can perform SQL query without using model file by following Magento coding standards? Yes! When there is a will, there is a way too. Here is I have performed delete SQL query to show you a demo that how you can delete a particular number of rows/records without using a model file in Magento 2.
To do this I have created on ‘Index.php’ file inside my extension folder at this path using below code.
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>
That’s it. Using this code you can perform similar different SQL operations without creating standard Magento 2 Model file.
Lastly, if you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends and Let us know if you are facing any issue while implementing this code.
Happy Coding!
Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…
MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…
In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…
Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…
The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…
Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…