有时您可能需要从您看到的特定产品中收集整个产品列表或产品类别。可以使用快速解决方案来获取产品类别,而无需在您的网站内来回切换。您将以省时且准确的方式从任何您想要的产品中获得类别。

现在让我们看看如何从 Magento 2 中的特定产品获取类别。此方法使您能够根据需要从当前或任何产品中获取列表。

首先,您需要打开我的自定义模块(Example_HelloWorld)的块类,然后在该块类的构造函数中注入\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory,\Magento\Catalog\Model\ProductRepository和类的对象。\Magento\Framework\Registry

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

<?php
namespace Example\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{    
    protected $_categoryCollectionFactory;
    protected $_productRepository;
    protected $_registry;
        
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
        \Magento\Catalog\Model\ProductRepository $productRepository,
        \Magento\Framework\Registry $registry,
        array $data = []
        )
        {
            $this->_categoryCollectionFactory = $categoryCollectionFactory;
            $this->_productRepository = $productRepository;
            $this->_registry = $registry;
            parent::__construct($context, $data);
    }
    
    /**
     * Get category collection
     *
     * @param bool $isActive
     * @param bool|int $level
     * @param bool|string $sortBy
     * @param bool|int $pageSize
     * @return \Magento\Catalog\Model\ResourceModel\Category\Collection or array
     */
    public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
    {
        $collection = $this->_categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*');        
        
        // select only active categories
        if ($isActive) {
            $collection->addIsActiveFilter();
        }
                
        // select categories of certain level
        if ($level) {
            $collection->addLevelFilter($level);
        }
        
        // sort categories by some value
        if ($sortBy) {
            $collection->addOrderField($sortBy);
        }
        
        // select certain number of categories
        if ($pageSize) {
            $collection->setPageSize($pageSize); 
        }    
        
        return $collection;
    }
    
    public function getProductById($id)
    {        
        return $this->_productRepository->getById($id);
    }
    
    public function getCurrentProduct()
    {        
        return $this->_registry->registry('current_product');
    }
}
?>

如果您想使用当前产品,则该getCurrentProduct()功能处于活动状态。如果来自任何特定项目,请启用getProductById($id)该功能。之后,您可以从链接到该产品的类别 ID 中检索类别的集合。在该.phtml文件中,您需要添加以下代码片段:

$productId = 1; // YOUR PRODUCT ID
$product = $block->getProductById($productId);
 
// for current product
// $product = $block->getCurrentProduct();
 
$categoryIds = $product->getCategoryIds();
 
$categories = $block->getCategoryCollection()
                    ->addAttributeToFilter('entity_id', $categoryIds);
                    
foreach ($categories as $category) {
    echo $category->getName() . '<br>';
}