Get product collection with product ids

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.


Use SearchCriteria and Product Repositories:

$productIds = [.....];
$searchCriteria = $this->searchCriteriaBuilder
                ->addFilter('entity_id', $productIds, 'in')
                ->create();

$products = $this->productRepositoryInterface->getList($searchCriteria)->getItems();

To get search criteria builder and product repository object you have to require:

  • Magento\Framework\Api\SearchCriteriaBuilder
  • Magento\Catalog\Api\ProductRepositoryInterface