How do you load product by product ID in Magento2?
Using Repository to Load Products – Recommanded
1 2 |
$productRepo = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface'); $product = $productRepo->getById(1); |
Using Factroy to Load Products
1 2 |
$productFactory = $objectManager->create('\Magento\Catalog\Model\ProductFactory'); $product = $productFactory->create()->load(1); |
The reason to use ProductRepository’s instead of a ProductFatory’s to load the product is because the former is of a higher level than the latter.
SO, you should use the API layer whenever possible, because:
- Api/Data layer is used in the Web Api, as well
- models can – and probably will – be refactored at some point; Api/Data/Product will not.
- To get a product in your classes, you need to inject either a concrete factory (ProductFactory) or an interface (ProductRepository). I don’t think you want your module to rely on anything but an interface. Hence I disagree with this type of injection.
Using Collection to Load Products
If you need to load multiple products, you should use prodcut collections.
1 2 3 4 5 6 7 8 9 10 11 12 |
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection'); $productCollection->addAttributeToSelect('*') ->addFieldToFilter('entity_id', array('in' => array(1,2,3,4))); // get first product in the collection if ($productCollection->getSize()){ $product = $productCollection->getFirstItem(); } // get all products in the collection foreach ($productCollection as $product) { // your logic here } |
Using Product Mode to Load Products – Deprecated
1 |
$product =$objectManager->create('Magento\Catalog\Model\Product')->load(3); |