Magento2 – How to Get Distinct List of Specified Attribute Using Product Collection

magento-2.1magento2

Need to get distinct list of product manufacturers using product collection.

Manufacturer is an EAV attribute.
For example I have this data:

enter image description here

As a result preferable to recieve array list of manufacturers.

enter image description here

I'm trying to do something like this

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

    $productManufacturer = $objectManager->create('\Magento\Catalog\Model\Product');
    $manufacturerCollection = $productManufacturer->getCollection();
    $manufacturerCollection->addAttributeToSelect('manufacturer');
    $manufacturers = $manufacturerCollection->getSelect()->group('manufacturer');

Please, any advices how to implement this?

Best Answer

Did this using plain magento sql query.

class Index extends \Magento\Framework\View\Element\Template
{


protected $_resource;

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

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

    $result = $connection->fetchAll("SELECT DISTINCT cat.value FROM catalog_product_entity_varchar as cat 
            JOIN eav_attribute as eav ON eav.attribute_id=cat.attribute_id
            WHERE eav.attribute_code='manufacturer'");
}
Related Topic