Magento – Get product collection by root category and all its subcategories in Magento 2

categorycollection;magento2product

How can I retrieve a product collection by a root category and from all its subcategories?

Eg:

Root Category (2 products)

  • Subcategory 1 (2 products)
  • Subcategory 2 (3 products)

So I want to retrieve all 7 products in the collection.

Best Answer

You can use like this:

/** \Magento\Catalog\Api\CategoryRepositoryInterface */
protected $categoryRepository;

/** \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory */
protected $productCollectionFactory;

public function getAllProductOfSubcategories($categoryId, $storeId = null) {

    /** @var $result \Magento\Catalog\Model\ResourceModel\Product\Collection */
    $result = $this->productCollectionFactory->create();

    //get category at $storeId 
    try {
        $category = $this->categoryRepository->get($categoryId, $storeId);
    } catch (\Magento\Framework\Exception\NoSuchEntityException $noSuchEntityException) {
        return null;
    }

    return $result->addCategoryFilter($category);
}

*Note: Your category must Enable Anchor

Enable Anchor for Category

*Note: run php bin/magento indexer:reindex just for make sure

Related Topic