在 Magento 2 中获取产品集合

虽然在 Magento 2 中获取特定产品集合有不同的操作,但它们是加载、过滤(例如按属性)和排序。在本文中,我将仅介绍帮助您开始使用产品集合的基本步骤。以下是两个初始步骤:

  • 步骤一:在Example_HelloWorld区块中声明
  • 步骤 2:显示phtml文件中的产品集合

步骤一:在Example_HelloWorld区块中声明

您将使用 module 的块类,然后可能在模块的块类的构造函数中Example_HelloWorld注入 的对象。\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory

app/code/Example/HelloWorld/Block/HelloWorld.php

<?php
namespace Example\HelloWorld\Block;
class HelloWorld 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); // fetching only 3 products
        return $collection;
    }
}
?>

注:您可以请求产品集合的数量,数量是有限的或无限的。在实现该功能时,您需要根据需求扩展代码。

步骤 2:显示phtml文件中的产品集合

phtml使用以下代码打印文件中的产品集合:

$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
    print_r($product->getData());     
    echo "<br>";
}

现在,您可以获取请求的集合中每个产品的数据。