Magento2 如何在magento 2中获取模型和产品集合
如何在magento 2中加载模型 像Magento2 如何在magento 2中获取模型和产品集合,magento2,Magento2,如何在magento 2中加载模型 像 就像我们过去在magento 1一样 尝试此方法获取所有产品集合 <?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory'); $c
就像我们过去在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>';
}
?>
建议使用依赖项注入,而不是直接使用对象管理器。例子: 在块文件中,可以使用以下代码返回产品集合:
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;
}
它返回[]。为什么?这是使用依赖注入的正确方法+1您好@Manashvi,我想介绍这些产品/cache/1d4ec593232a3f40f7a929d5b10820a2/u/g/ug03-bk-0.jpgimages@shivashankarm首先,为什么?它在缓存中,如果你清除了缓存,那么URL就改变了,其他的都改变了。我怀疑你现在已经明白了,但你不应该引用存储在缓存中的图像
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;
}