Is it possible to get a product collection bassd on array of product ids?
3 Answers
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.
-
1Maybe I'm missing something but using repositories doesn't seem to allow full control on the result; for example: how do you add an attribute to EAV entities? Or join an external table? In that case I still see Magento2 core uses collections. Is there a valid alternative? Thank you! Commented Jun 7, 2016 at 8:01
-
1Unfortunately there is not. There are often cases where you still need collections. See also: magento.stackexchange.com/a/158098/243 Commented Jul 19, 2017 at 11:36
-
Exactly my problem now. I built a working method to get a result with repository and the result could not be modified (or even put into a collection neatly, missing add/set data methods... and many other issues). Commented Aug 11, 2017 at 9:48
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
-
I want to get the product collection from my entity ids, Please give me full code or idea!– SushivamCommented Aug 8, 2016 at 5:05
$porductIds=array(2,6,7);
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$collectionByIds = $productCollection->addAttributeToSelect('*');
$collectionByIds->addFieldToFilter('entity_id', array('in' => $data));
$collectionByIds->load();
foreach ($collectionByIds as $collection) :
echo "<pre>";
print_r($collection->getName());
endforeach;