Magento 2-在左联接中使用group_concat选择

时间:2018-12-19 12:11:54

标签: mysql magento2

我目前正在尝试将订单产品中的SKU放入订单网格和后端的过滤器中。它已经在工作,但仅适用于一个SKU,而不是订单中的所有SKU。我的控制器如下所示:

<?php
namespace Vendor\Module\Model\ResourceModel\Order\Grid;

use Magento\Sales\Model\ResourceModel\Order\Grid\Collection as OriginalCollection;
use Magento\Framework\Data\Collection\Db\FetchStrategyInterface as FetchStrategy;
use Magento\Framework\Data\Collection\EntityFactoryInterface as EntityFactory;
use Magento\Framework\Event\ManagerInterface as EventManager;
use Psr\Log\LoggerInterface as Logger;

class Collection extends OriginalCollection
{
    protected $_authSession;
    public function __construct(
       EntityFactory $entityFactory,
       Logger $logger,
       FetchStrategy $fetchStrategy,
       EventManager $eventManager,
       \Magento\Backend\Model\Auth\Session $authSession
      )
    {        
       $this->_authSession = $authSession;
       parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager);
    }

    protected function _renderFiltersBefore() {
        $user = $this->_authSession->getUser();
        $joinTable = $this->getTable('sales_order_item');
        $this->getSelect()->joinLeft($joinTable, 'main_table.entity_id = sales_order_item.order_id', ['sku'])->group('entity_id');
        parent::_renderFiltersBefore();
    }
}

现在我的问题:是否可以在左联接中选择数据作为group_concat?如果是这样,请给我一个提示。 我已经尝试过了

$this->getSelect()->joinLeft($joinTable, 'main_table.entity_id = sales_order_item.order_id', ['sku' => new \Zend_Db_Expr('group_concat(`sales_order_item`.sku SEPARATOR ",")')]);

但是没有用。

1 个答案:

答案 0 :(得分:3)

自己解决。缺少的是GROUP BY语句,因此我在查询中添加了->group('entity_id')。我还放下了分隔符。

$this->getSelect()->joinLeft($joinTable, 'main_table.entity_id = sales_order_item.order_id', ['sku' => new \Zend_Db_Expr('group_concat(`sales_order_item`.sku)')])->group('entity_id');