Magento, Magento 2

Magento 2 : Get Product Collection

Magento 2 How to get product colleciton

In this technical blog, we will see different ways of get product collection in Magento 2. Nowadays, Somewhere in every project developers need to get product collection with many conditions. In other words, There are lots of ways and filters available to get product collection for details of products. Here, we will see how to get product collection with filters, sorting, etc.

First of all, let’s do how to load product collection. To create custom module, you can click here.

1) Load product collection :

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\HelloWorld\Block;

class HelloWorld extends \Magento\Framework\View\Element\Template
{
    protected $productCollectionFactory;
    protected $categoryFactory;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        array $data = []
    ) {
        $this->productCollectionFactory = $productCollectionFactory;
        $this->categoryFactory = $categoryFactory;
        parent::__construct($context, $data);
    }

    public function getProductCollection()
    {
        $collection = $this->productCollectionFactory->create();
        $collection->setPageSize(3);
        foreach ($collection as $product)
        {
            print_r($product->getData());
        }
        return $collection;
    }
}

Firstly, change below all types of code as per requirement in getProductCollection() function.

2) Load product collection with specific attribute :

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect(['name','sku']);
$collection->setPageSize(3);
foreach ($collection as $product)
{
    print_r($product->getData());
}

3) Load product collection with all attribute :

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(3);
foreach ($collection as $product)
{
    print_r($product->getData());
}

4) Get product collection by multiple categories :

$categories = [1,2,3]; //category ids array
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoriesFilter(['in' => $categories]);
return $collection;

5) Get product collection by specific category :

$categoryId = '1';
$category = $this->categoryFactory->create()->load($categoryId);
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoryFilter($category);
$collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
return $collection;

6) Get product collection by product type :

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addAttributeToFilter('type_id', ['eq' => 'simple']);
$collection->getSelect()->order('created_at', \Magento\Framework\DB\Select::SQL_DESC);
$collection->getSelect()->limit(10);
return $collection;

You can add below text also as value of type_id for different product type filter :

  • simple = Filter of simple product
  • configurable = Filter of configurable product
  • grouped = Filter of grouped product
  • virtual = Filter of virtual product
  • bundle = Filter of bundle product

7) Get product collection by store id :

$storeid = 1;
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addStoreFilter($storeid);
return $collection;

8) Get product collection by website ids :

$website_ids = [1,2];
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addStoreFilter($storeid);
$collection->addWebsiteFilter($websiteIds);
return $collection;

9) Filter Product Collection :

Is equal to :

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('status', ['eq' => 1]);

Is not equal to :

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('status', ['neq' => 1]);

Greater than :

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['gt' => 100]);

Greater than equal to :

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['gteq' => 100]);

Less than :

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['lt' => 100]);

Less than equal to :

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['lteq' => 100]);

Like :

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('sku', ['like' => '%Bag%']);

Not Like :

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('sku', ['nlike' => '%Bag%']);

In Array :

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('entity_id', ['in' => [1,2]]);

Not in Array :

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('entity_id', ['nin' => [1,2]]);

NULL :

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('description', ['null' => true]);

NOT NULL :

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('description', ['notnull' => true]);

Sort Product Collection :

Order by ASC :

$collection = $this->productCollectionFactory->create();
$collection->setOrder('sku', 'ASC');

OR

$collection = $this->productCollectionFactory->create();
$collection->getSelect->order('sku', 'ASC');

Order by DESC :

$collection = $this->productCollectionFactory->create();
$collection->setOrder('sku', 'DESC');

OR

$collection = $this->productCollectionFactory->create();
$collection->getSelect->order('sku', 'DESC');

Set Limit Product Collection :

$collection = $this->productCollectionFactory->create();
$collection->setPageSize(50)->load();

Set Limit Product Collection with Current Page :

$collection = $this->productCollectionFactory->create();
$collection->setPageSize(50)->setCurPage(2)->load();

Count Product Collection :

$collection = $this->productCollectionFactory->create();
echo $collection->count();

Group by Product Collection :

$collection = $this->productCollectionFactory->create();
$collection->getSelect()->group('entity_id');

Print Collection Query :

$collection = $this->productCollectionFactory->create();
echo $collection->getSelect()->__toString();

I hope this technical blog helped you find all ways of get product collection in Magento 2. Save this page for your future reference. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution 🙂

Tagged , ,