5

How to load product collection in Magento 2 and what is the difference between Magento 1 and Magento 2 load product collection

8

The standard collections are actually very similar. There are other similar structures, but for products you can load them in and load them just like Magento 1. Just like in Magento 1, if you are using the collection via iteration you do not have to load it as it's done implicitly.

As always in Magento 2, you should be injecting classes via dependency injection in your class constructor. Plus, if you are going to create more than one instance you can add "Factory" after any class and you'll get a wrapping class that allows you to generate as many as you want.

Here is the use of both together:

/** @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory */
protected $collectionFactory;

public function __construct(
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory
) {
    $this->collectionFactory = $collectionFactory;
}

public function yourMethod()
{
    // Use factory to create a new product collection
    $productCollection = $this->collectionFactory->create();
    /** Apply filters here */
    $productCollection->addAttributeToSelect('*');
    // Don't have to do this
    // $productCollection->load();

    foreach ($productCollection as $product){
         echo 'Name  =  '.$product->getName().'<br>';
    }  
}

With thanks to @megi for the example usage code in their answer.

4
 <?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection */
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
/** Apply filters here */
$collection = $productCollection->addAttributeToSelect('*')
            ->load();

foreach ($collection as $product){
     echo 'Name  =  '.$product->getName().'<br>';
}  
?>
  • 4
    It is not recommended to use the objectManager directly, try to use factorys instead as Robert Egginton suggested. – TrytoFly Oct 12 '17 at 10:18
4

Here is the best way to get product collection in magento

public function __construct(
        \Magento\Catalog\Model\Product $product
    )
{
    $this->product = $product;
}

public function getCollection()
{
    $collection = $this->product->create()->getCollection();
    return $collection;
}

public function loadProduct($id)
{
    $product = $this->product->create()->load($id);
    return $product;
}

In the magento 1 you can get collection using below code

$productCollection = Mage::getModel('catalog/product')->getCollection();

here we call Model catalog/product and then getCollection() method to get all product collection

In Magento 2 First we need to call class of product collection Magento\Catalog\Model\Product

then we need to call method create(); Magento 2's create method is same as Magento 1's getModel then we call collection.

3

=> Magento 1 :

$products = Mage::getModel('catalog/product')->getCollection();
foreach($products as $prod) {
$product = Mage::getModel('catalog/product')->load($prod->getId());
}

=> Magento 2 :

public function __construct(
    \Magento\Backend\Block\Template\Context $context,        
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
    array $data = []
)
{    
    $this->_productCollectionFactory = $productCollectionFactory;    
    parent::__construct($context, $data);
}

 public function getProductCollection()
{
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->setPageSize(3); // fetching only 3 products
    return $collection;
}
  • how to get new product collection only? – jafar pinjar Feb 8 at 11:21
2

The best way to load the product collection using repositories in Magento 2 service contracts.

Inject the interface Magento\Catalog\Api\ProductRepositoryInterface in your constructor as follows

protected $productRepo; 

public function __construct(    
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepo
) {
    $this->productRepo = $productRepo;
}

public function getProductById($itemId)
{
    return $this->productRepo->getById($itemId);
}

public function getProductBySku($sku)
{
    return $this->productRepo->get($sku);
}
1

Magento 2 getting the product is totally different from Magento 1. in Magento 1 we use this code to get the collection.

$productCollection = Mage::getModel('catalog/product')->getCollection();

To get product collection in Magento 2 use following code.

 protected $_productCollectionFactory;

 public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
    ) {
        $this->_productCollectionFactory = $productFactory;
    }
    public function getProductCollection()
    { 
      return   $this->_productCollectionFactory->create(); 

     }

Reference

  • Hello, Is it possible to apply this new product collection throughout the website ? – inrsaurabh Jun 17 '18 at 17:30
  • how to filter with most order items, i used below code, its not working, ->setOrder('ordered_qty', 'desc'); – jafar pinjar Jan 11 at 8:37
  • @jafarpinjar use order item collections – Qaisar Satti Jan 11 at 8:44
  • @QaisarSatti, i am getting product collection with category filter, how to use with this? – jafar pinjar Jan 11 at 8:49
  • @jafarpinjar that is not related to this answer. create new question for that – Qaisar Satti Jan 11 at 8:53
0

Try this one it's working for me.

$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$productCollection = $_objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

$collection = $productCollection->create()

 ->addAttributeToSelect('*')

 ->addAttributeToFilter('status', '1')

 ->load();
0

  1. List item
public function __construct(
    \Magento\Backend\Block\Template\Context $context,        
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
    array $data = []
)
{    
    $this->_productCollectionFactory = $productCollectionFactory;    
    parent::__construct($context, $data);
}

 public function getProductCollection()
{
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    return $collection;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.