Cara memanggil Direct SQL Queries dan bergabung ke koleksi Di Magento2

13

Saya hanya ingin memanggil kueri sql langsung di Magento2 seperti di magento1.x

Pradeep Kumar
sumber

Jawaban:

17

Dalam Anda memblokir atau memodelkan file Anda perlu menginisialisasi sumber daya maka Anda perlu memanggil koneksi

itu adalah

protected $_resource;

dan

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

untuk koneksi

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

    return $this->connection;
}

di bawah ini adalah contoh dalam file blok

<?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; 
    }
}
Pradeep Kumar
sumber
2
\Magento\Framework\App\Resourcetidak ada (setidaknya tidak dalam 2.1.3). Bukankah maksud Anda ResourceConnection?
Giel Berkers
Harap perbarui jawaban sesuai dengan versi yang lebih baru karena ini sepertinya benar, tetapi tidak berfungsi di Magento 2.1.5.
Max
10

Anda telah menggunakan panggilan lama untuk versi beta core_write dan core_read di rc seperti ini:

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

  }

dapatkan adaptor:

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

dapatkan tabel dan pilih:

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

menyelesaikan kursus dari sini

Ibnab
sumber
6

Saya telah mencapai ini dengan cara berikut. Saya memiliki file khusus tempat saya membuat objeknya dan itu berfungsi. Periksa sekali.

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

}

Coba dan beri tahu saya jika itu berhasil untuk Anda.

Rahul Anand
sumber
Bekerja, dari pengontrol.
Zulkhaery Basrul
9
Jangan gunakan manajer objek tetapi injeksi ketergantungan sebagai gantinya.
Giel Berkers
1

Tidak bekerja untuk saya :(

Ini file blokir saya:

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

}

Saya mendapatkan kesalahan ini: Obyek DOMDocument harus dibuat.

Apa yang saya lewatkan?

Sanjay
sumber
bukan jawaban. Juga, saya tidak yakin apa yang tidak berhasil. Anda tidak menggunakan $ connection-> fetchAll () misalnya di mana saja
Maciej Paprocki
1
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);
Rakesh Jesadiya
sumber
2
Jangan menyuntikkan manajer DI. Suntikkan ketergantungan . Entah Test\Vendor\Model\VendorFactoryatau Test\Vendor\Model\Vendor\Collection.
nevvermind
0

coba yang ini :

    //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());
    }
Manish
sumber
1
Tolong jelaskan apa yang kode Anda lakukan dan bagaimana menyelesaikan masalah OP (bagian mana dari kode tersebut secara spesifik).
7ochem
0
<?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); ?>
Divya
sumber