How can I write custom query in Magento 2 format I need following query in Magento 2 format,
SELECT * FROM ( SELECT * FROM TABLE_NAME WHERE customer_id IN ( 0, 5 ) ORDER BY feed_id DESC ) AS t1 GROUP BY position limit 0,5
How can I write custom query in Magento 2 format I need following query in Magento 2 format,
SELECT * FROM ( SELECT * FROM TABLE_NAME WHERE customer_id IN ( 0, 5 ) ORDER BY feed_id DESC ) AS t1 GROUP BY position limit 0,5
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;
}