Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get model and product collection in magento 2

Tags:

magento2

How to load the model in magento 2 like

Mage::getModel('catalog/product')->load()

as we used to get in magento 1.

like image 466
Rahul Singh Avatar asked Jan 12 '16 10:01

Rahul Singh


1 Answers

It is recommended to use dependency injection rather than directly using object Manager. Example: In your block file you can use following code to return product collection:

public function __construct(
        \Magento\Framework\View\Element\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();
        return $collection;
    }
like image 185
amitshree Avatar answered Oct 25 '22 00:10

amitshree