Magento2 Product Collection – How to Get Product Collection with Product IDs

magento2product-collection

Is it possible to get a product collection bassd on array of product ids?

Best Answer

Given an instantiated but not loaded collection $collection and an array of product ids $productIds, you can use addIdFilter() just as in Magento 1:

$collection->addIdFilter($productIds);

To instantiate a collection, you can inject a \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory and then use

$collection = $this->collectionFactory->create();

But this is not recommended practice anymore!


In Magento 2, you should not think too much in terms of collections anymore when using core modules, they are a mere implementation detail. Use the service contracts instead:

  • Inject Magento\Catalog\Api\ProductRepositoryInterface and \Magento\Framework\Api\SearchCriteriaBuilder
  • use Magento\Framework\Api\Filter;
  • Build a search criteria and pass it to $productRepository->getList():

    $searchCriteria = $this->searchCriteriaBuilder->addFilter(new Filter([
        Filter::KEY_FIELD => 'entity_id',
        Filter::KEY_CONDITION_TYPE => 'in',
        Filter::KEY_VALUE => $productIds
    ]))->create();
    $products = $this->productRepository->getList($searchCriteria)->getItems();
    

    $products then is an array of products.