如何在Magento2中调用直接SQL查询并加入集合


Answers:


18

在块或模型文件中,您需要初始化资源,然后需要调用连接

那是

protected $_resource;

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

用于连接

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

    return $this->connection;
}

下面是块文件中的示例

<?php
/**pradeep.kumarrcs67@gmail.com*/
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; 
    }
}

2
\Magento\Framework\App\Resource不存在(至少在2.1.3中不存在)。不是ResourceConnection
Giel Berkers

请将此答案更新为较新的版本,因为这似乎是正确的,但在Magento 2.1.5中不起作用。
Max

11

您已经在rc中使用B​​eta版本的core_write和core_read的旧调用是这样的:

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

  }

获取适配器:

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

获取表并选择:

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

这里完成课程


6

我已经通过以下方式实现了这一目标。我有一个自定义文件,可以在其中创建对象并起作用。检查一次。

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

}

尝试让我知道它是否适合您。


从控制器工作。
Zulkhaery Basrul

9
不要使用对象管理器,而是依赖注入。
Giel Berkers

1

对我不起作用:(

这是我的阻止文件:

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

}

我收到此错误:应该创建对象DOMDocument。

我想念什么?


没有答案。另外,我不确定什么不起作用。您不会在任何地方使用$ connection-> fetchAll()
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);

2
不要注入DI经理。注入依赖项。无论是Test\Vendor\Model\VendorFactoryTest\Vendor\Model\Vendor\Collection
nevvermind 2015年

0

试试这个:

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

1
请描述您的代码在做什么以及它如何解决OP的问题(具体是代码的哪一部分)。
7ochem '16

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); ?>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.