1

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
1
  • Let me know if you have any issue. Commented Jul 7, 2017 at 17:00

1 Answer 1

2

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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.