17

I just want to call direct sql query in Magento2 as like in magento1.x

Priya
851 silver badge15 bronze badges
asked Oct 29, 2015 at 4:34

7 Answers 7

20

In you block or model files you need to initialize resource then you need to call connection

that is

protected $_resource;

and

public function __construct(
 \Magento\Backend\Block\Template\Context $context,
 \Magento\Framework\App\Resource $resource,
 array $data = []
) {
 $this->_resource = $resource;
 parent::__construct($context, $data);
}

for connection

protected function getConnection()
{
 if (!$this->connection) {
 $this->connection = $this->_resource->getConnection('core_write');
 }
 return $this->connection;
}

below is example in block file

<?php
/**[email protected]*/
namespace Sugarcode\Test\Block;
class Joinex extends \Magento\Framework\View\Element\Template
{
 protected $_coreRegistry = null;
 protected $_orderCollectionFactory = null;
 protected $connection;
 protected $_resource;
 public function __construct(
 \Magento\Backend\Block\Template\Context $context,
 \Magento\Framework\Registry $registry,
 \Magento\Framework\App\Resource $resource,
 \Magento\Sales\Model\Resource\Order\CollectionFactory $orderCollectionFactory,
 array $data = []
 ) {
 $this->_orderCollectionFactory = $orderCollectionFactory;
 $this->_coreRegistry = $registry;
 $this->_resource = $resource;
 parent::__construct($context, $data);
 }
 public function _prepareLayout()
 {
 return parent::_prepareLayout();
 }
 protected function getConnection()
 {
 if (!$this->connection) {
 $this->connection = $this->_resource->getConnection('core_write');
 }
 return $this->connection;
 }
 public function getDirectQuery()
 {
 $table=$this->_resource->getTableName('catalog_product_entity'); 
 $sku = $this->getConnection()->fetchRow('SELECT sku,entity_id FROM ' . $table);
 return $sku;
 }
 public function getJoinLeft()
 {
 $orders = $this->_orderCollectionFactory->create();
 $orders->getSelect()->joinLeft(
 ['oce' => 'customer_entity'],
 "main_table.customer_id = oce.entity_id",
 [ 
 'CONCAT(oce.firstname," ", oce.lastname) as customer_name',
 'oce.firstname',
 'oce.lastname',
 'oce.email'
 ]
 );
 //$orders->getSelect()->__toString(); $orders->printlogquery(true); exit;
 return $orders; 
 }
}
answered Oct 29, 2015 at 4:39
2
  • 2
    \Magento\Framework\App\Resource does not exist (at least not in 2.1.3). Don't you mean ResourceConnection? Commented Jan 28, 2017 at 21:08
  • Please update the answer accordingly to newer version as this seems to be right, but not working in Magento 2.1.5. Commented Mar 28, 2017 at 23:17
14

you have use old call for beta version core_write and core_read in rc is like this :

 protected _resource;
 public function __construct(Context $context,
\Magento\Framework\App\ResourceConnection $resource)
 {
 $this->_resource = $resource;
 parent::__construct($context);
 }

get adapter :

$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);

get table and select:

$tblSalesOrder = $connection->getTableName('sales_order');
$result1 = $connection->fetchAll('SELECT quote_id FROM `'.$tblSalesOrder.'` WHERE entity_id='.$orderId);

complete course from here

answered Dec 29, 2015 at 14:05
7

I have achieved this in following way. I have a custom file where I am creating object of it and it worked. Check it once.

class Sample extends \Magento\Framework\App\Http implements \Magento\Framework\AppInterface
{
 public function sampleMethod()
 {
 $connection = $this->_objectManager->create('\Magento\Framework\App\ResourceConnection');
 $conn = $connection->getConnection();
 $select = $conn->select()
 ->from(
 ['o' => 'catalog_category_entity_varchar']
 )
 ->where('o.value=?', '2');
 $data = $conn->fetchAll($select);
 print_r($data);
 }
}

Try and let me know if it works for you.

Josh Davenport-Smith
9991 gold badge10 silver badges22 bronze badges
answered Dec 21, 2015 at 11:47
2
  • Work, from controller. Commented Mar 10, 2016 at 7:40
  • 10
    Don't use the object manager but dependency injection instead. Commented Jan 27, 2017 at 13:49
2
For Join Query,
 protected $_objectManager; 
 public function __construct(
 \Magento\Framework\ObjectManagerInterface $objectManager,
 \Test\Vendor\Model\ResourceModel\Vendor $resourceModel
 ) {
 $this->resourceModel = $resourceModel;
 $this->_objectManager = $objectManager;
 }
$collection = $this->_objectManager->create('Test\Vendor\Model\Vendor')->getCollection();
$vendor_id = 5; //get dynamic vendor id
 $collection->getSelect()->join('secondTableName as s2','main_table.entity_id = s2.vendor_id', array('*'))->where("main_table.entity_id = ".$vendor_id);
answered Nov 4, 2015 at 7:11
1
  • 2
    Don't inject the DI manager. Inject the dependency. Either Test\Vendor\Model\VendorFactory or Test\Vendor\Model\Vendor\Collection. Commented Nov 9, 2015 at 20:36
2
<?php 
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
 $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
 $connection = $resource->getConnection();
 $tableName = $resource->getTableName('table_name');
 $attribute_information = "Select * FROM " . $tableName; //check for the custom attribute condition". WHERE id = " . $manufacture . ";";
// fetchOne it return the one value
$result = $connection->fetchOne($attribute_information); ?>
answered Apr 29, 2019 at 13:09
1
1

Does not work for me :(

Here is my block file:

<?php
namespace Silver\Customize\Block;
use \Magento\Framework\View\Element\Template;
class Main extends Template
{ 
 protected $connection;
 protected $_resource; 
 public function __construct(
 \Magento\Backend\Block\Template\Context $context,
 \Magento\Framework\App\Resource $resource
 ) {
 $this->_resource = $resource;
 parent::__construct($context, $data);
 } 
 protected function _prepareLayout()
 {
 $this->setMessage('Hello');
 $this->setName($this->getRequest()->getParam('name')); 
 }
 public function getGoodbyeMessage()
{
 return 'Goodbye World';
}
 protected function getConnection()
 {
 if (!$this->connection) {
 $this->connection = $this->_resource->getConnection('core_write');
 }
 return $this->connection;
 } 
}

I get this error: Object DOMDocument should be created.

What am I missing?

answered Dec 29, 2015 at 13:58
1
  • not an answer. Also, I am not sure what doesn't work. You don't use $connection->fetchAll() for example anywhere Commented Jul 26, 2016 at 9:21
0

try this one :

 //for print log on custom log file.
 $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/mylog.log');
 $logger = new \Zend\Log\Logger();
 $logger->addWriter($writer);
 $logger->info('Query cron srarting...: ');
 try{
 $themeId=273;
 $this->_resources = \Magento\Framework\App\ObjectManager::getInstance()
 ->get('Magento\Framework\App\ResourceConnection');
 $connection= $this->_resources->getConnection();
 $negotiateTable = $this->_resources->getTableName('table_name');
 $sql = "Select * FROM " . $negotiateTable;//". WHERE id = " . $themeId . ";";
 $result = $connection->fetchAll($sql);
 foreach ($result as $item){
 $logger->info('Query cron query data...: '.json_encode($item));
 }
 }catch (\Exception $e){
 $logger->info('Query cron query data exception'.$e->getMessage());
 }
answered Apr 4, 2016 at 12:17
1
  • 1
    Please describe what your code is doing and how it is solving the OP's problem (what part of the code specifically). Commented Apr 4, 2016 at 12:40

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.