Magento Expert Forum - Improve your Magento experience

Results 1 to 2 of 2

How can I write custom query in Magento 2 format

  1. #1

  2. #2
    Junior Member kajal's Avatar
    Join Date
    Sep 2014
    Location
    Bangalore
    Posts
    402
    Thanks
    0
    Thanked 7 Times in 7 Posts

    Default

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

  3. The Following User Says Thank You to kajal For This Useful Post:

    alanclarc143 (12-08-2017)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •