Magento 2 get product collection
In this tutorial I show you how to get product collection for your Magento 2 shop. A product collection gets you all needed product information and can be filtered by all product attributes.
Magento 2 get product collection
An online shop is based around one important thing: the product. The most important code snippet you will use is to get product collection mostly filtered to get a small collection. There are different ways to do that. One recommended way is to load a collection by factory. A factory is a design pattern, a class that is specialized in getting class instances. A product collection factory for instance generates product collections for you. You can do this the following way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | namespace MyCompany\MyModule\Block; class MyModule extends \Magento\Framework\View\Element\Template { protected $_productCollectionFactory; 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); // limit collection to only 3 products return $collection; } } |
We create a new Magento 2 block an inject \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory class. This is needed to get a collection from factory. A getProductCollection returns a new product collection. This method does the following:
- create a new collection from collection factory
- filter attributes (collumns)
This time we want to load all data (*), you can also add a comma seperated list of attribute names. Only this attributes get loaded – lazy loading optimizes your database select statement. - filter by attribute values
It is possible to filter your collection by loaded attribute values. For example all products with price small than 1000 $. My example use setPageSize() to only load a given number of products.
Conclusion
Loading a product collection is by far the most common usage in Magento 2. You are able to customize your collection and speed up database connection and loading time of your product list sites.