1

Please, how we can use sql queries on controller? i am using Magento 2 and this is my controller:

<?php

namespace Demo\Demo\Controller\Demo;


class Demo extends \Magento\Framework\App\Action\Action
{

    public function execute()
    {

    }
}
4

2 Answers 2

2

You can use ResourceConnection Method if you wish to use sql queries in Controller.

  $resource = $this->_objectManager->create('\Magento\Framework\App\ResourceConnection');
  $connection = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);
  $values = $connection->fetchAll('select * from `table` ');
1
  • 7
    I disagree for two reasons: one should never use the object manager directly and every SQL queries must always be executed from the resource models that's their purpose Jun 11, 2016 at 8:45
4

You should not do it in controller. ResourceModel Layer is resposible for data persistence

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.