Magento 2 use custom query
Today we will discuss how in Magento 2 custom query works. Sometime magento 2 model is not enough to get data from database as per our requirements. So to fulfill this requirement we use custom query. In this example we will use select custom query, custom delete query, custom insert query and custom update query. So let’s start with example.
Get connection
First of all we will establish a connection to execute the query.
$connection= $this->_resources->getConnection();
Insert Query
It is simple to use insert query just set the values for columns. Use the inset method.
$connection->insert($this->_resources->getTableName(test_table), $array);
Select Query
Selecting table data in custom query you can use following code.
$result = $connection->fetchAll($select);
foreach ($result as $data) {
echo $data['id'];
}
Update Query
Updating table data in custom query you can use following code.
$sql = "Update " . $this->_resources->getTableName('test_table') . " Set `title` ='test title' where `id` = ".$id;
$connection->query($sql);
Delete Query
To delete table data in custom query you can use following code.
$condition = $this->getConnection()->quoteInto('id = ?', $id);
$this->getConnection()->delete($this->getTable('test_table'), $condition);
Join Table
To join table in custom query you can use following code.
['test_table1' => $this->_resources->getTableName('test_table1')],
'o.id = test_table1.id',
['column1','column2']
);
One thought on “Magento 2 use custom query”
Leave a Reply
You must be logged in to post a comment.
Very well explained and articulated , waiting to hear more on this topic.