如何在 magento 2 中获取模型和产品集合

How to get model and product collection in magento 2

如何在 magento 2 中加载模型 喜欢

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

就像我们在 magento 1 中一样。

试试这个获取所有产品集合

<?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>';
}  

?>

建议使用依赖注入而不是直接使用对象管理器。例子: 在您的块文件中,您可以使用以下代码来 return 产品集合:

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;
    }