Magento Expert Forum - Improve your Magento experience
-
How can I write custom query in Magento 2 format
Hello folks,
I would like to know, How can I write custom query in Magento 2 format ??
Book Ad in Times of India | Newspaper Ad Agency in Delhi
View more threads in the same category:
Last edited by vishnu; 13-03-2019 at 08:15 AM.
-
-
Junior Member
With ObjectManager:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance( ); // Instance of object manager
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection') ;
$connection = $resource->getConnection();
$tableName = $resource->getTableName('your_table_name'); //gives table name with prefix
$sql = "SELECT * FROM ( SELECT * FROM ".$tableName." WHERE customer_id IN ( 0, 5 ) ORDER BY feed_id DESC ) AS t1 GROUP BY position limit 0,5";
$result = $connection->fetchAll($sql);
With Factory Method:
<?php
protected $_resourceConnection;
public function __construct(
...
\Magento\Framework\App\ResourceConnection $resourceConnection,
...
) {
...
$this->_resourceConnection = $resourceConnection;
...
}
public function getTableName()
{
return $this->_resourceConnection->getTableName('your_table_name');
}
public function getCollection()
{
$tablename = $this->getTableName();
$connection = $this->_resourceConnection->getConnection();
$query = "SELECT * FROM ( SELECT * FROM ".$tablename." WHERE customer_id IN ( 0, 5 ) ORDER BY feed_id DESC ) AS t1 GROUP BY position limit 0,5";
$result = $connection->fetchAll($query);
return $result;
}
-
The Following User Says Thank You to kajal For This Useful Post:
alanclarc143 (12-08-2017)
-
Easy-To-Use, Multi-Channel Enterprise Commerce for your Business. Cost-Saving & Headache-Free Enterprise Ecommerce. Migrate to Shopify Plus®. $0 IT & Maintenance Cost.
-
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
Bookmarks