How to load the model in magento 2 like
Mage::getModel('catalog/product')->load()
as we used to get in magento 1.
Join Stack Overflow to learn, share knowledge, and build your career.
How to load the model in magento 2 like
Mage::getModel('catalog/product')->load()
as we used to get in magento 1.
Try this for get all product collection
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollection->create()
->addAttributeToSelect('*')
->load();
foreach ($collection as $product){
echo 'Name = '.$product->getName().'<br>';
}
?>
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;
}