Magento Expert Forum - Improve your Magento experience

Results 1 to 3 of 3

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
    1,446
    Thanks
    0
    Thanked 20 Times in 20 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)

  4. #3
    Junior Member
    Join Date
    Sep 2018
    Location
    Oman, Muscat
    Posts
    2,084
    Thanks
    0
    Thanked 4 Times in 4 Posts

    Default

    Easy-To-Use, Multi-Channel Enterprise Commerce for your Business. Cost-Saving & Headache-Free Enterprise Ecommerce. Migrate to Shopify Plus®. $0 IT & Maintenance Cost.

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
  •