Site icon MageComp Blog

How to write a Delete SQL query using Standard way without Model File in Magento 2

How to write a Delete SQL query using standard way without Model file in Magento 2

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!

Exit mobile version