In Magento 2, we can write sql query with help of ‘Magento\Framework\App\ResourceConnection’ class. you can write SQL queries like select, update, delete…
Here, we learning how to write SQL query in Magento 2 Standard way. let’s start to learn.
<?php namespace Mageclues\SqlQuery\Model\ResourceModel; use Magento\Framework\App\ResourceConnection; class Data { /** * @var ResourceConnection */ private $resourceConnection; public function __construct( ResourceConnection $resourceConnection ) { $this->resourceConnection = $resourceConnection; } /** * Select query to fetch records * * @return array */ public function selectQuery() { $tableName = $this->resourceConnection->getTableName('custom_entity'); //Init Connection $connection = $this->resourceConnection->getConnection(); $id = 99; $storeId = 1; $select = $connection->select() ->from( ['c' => $tableName], ['*'] ) ->where( "c.entity_id = :id" )->where( "c.store_id = :storeId" ); $records = $connection->fetchAll($select, $bind); return $records; } /** * Update query to edit records */ public function updateQuery() { $connection = $this->resource->getConnection(); $data = ["column_1"=>"value_1","column_2"=>"value_2"]; $id = 10; $where = ['entity_id = ?' => (int)$id]; $tableName = $connection->getTableName("custom_entity"); $connection->update($tableName, $data, $where); } /** * Delete query to remove records * * @return int */ public function deleteQuery() { $connection = $this->resource->getConnection(); $tableName = $connection->getTableName(custom_entity); $id = 10; $where = [ $connection->quoteInto('entity_id = ?', $id), ]; $deleteRows = $connection->delete($tableName, $where); return $deleteRows; } }
we hope this blog is useful for you. let me know in comment if you have any questions.
Thank you ):