Magento 2 : Get Product Collection based on Attribute

by Ankita Patel   Last Updated June 30, 2020 04:09 AM

I want to get product collection based on attribute.

For ex : If "Size" attribute exist in "Bag","Bottom" attribute set then, All Product's of Bag and Bottom return in product collection.

How to do that?

Any help would be appreciated.



Answers 2


Try Following way ..

<?php
namespace Rakesh\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{    
    protected $_productCollectionFactory;
        
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
        array $data = []
    )
    {    
        $this->_productCollectionFactory = $productCollectionFactory;    
        parent::__construct($context, $data);
    }
    
    public function getProductCollection()
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->addAttributeToFilter('size', array('in' => array("bag","bottom")));
        return $collection;
    }
}
?>
Rakesh Donga
Rakesh Donga
June 30, 2020 04:07 AM

You can use the Product Collection factory as below.

$_collection = $this->_productCollectionFactory->create();
$_collection->addAttributeToSelect('*');
$_collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
// Your attribute code   
$_collection->addAttributeToFilter('size',  array('notnull' => true));

Get your product.

foreach ($_collection as $_product) {
    $_product->getName();
}
Rizwan Khan
Rizwan Khan
June 30, 2020 04:07 AM

Related Questions


Filter products by website using AND

Updated July 14, 2015 13:04 PM




Magento 2, filtering product collection and sorting

Updated March 07, 2018 08:09 AM