Magento 2:获取父类别,子类别和产品数量

本文说明如何在Magento 2中获取父类别,子类别和该类别中的产品总数。

以下是我的自定义模块(Chapagain_HelloWorld)的块类。我在模块的块类的构造函数中注入了\ Magento \ Catalog \ Model \ CategoryFactory类的对象。

类的对象\ Magento的\目录\助手\目录\ Magento的\目录\型号\ CategoryRepository如在构造函数中也有使用。它们将用于打印类别和子类别的嵌套列表。

app / code / Chapagain / HelloWorld / Block / HelloWorld.php

<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{    
    protected $_categoryFactory;
    protected $_category;
    protected $_categoryHelper;
    protected $_categoryRepository;
        
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        \Magento\Catalog\Helper\Category $categoryHelper,
        \Magento\Catalog\Model\CategoryRepository $categoryRepository,        
        array $data = []
    )
    {
        $this->_categoryFactory = $categoryFactory;        
        parent::__construct($context, $data);
    }
    
    /**
     * Get category object
     * Using $_categoryFactory
     *
     * @return \Magento\Catalog\Model\Category
     */
    public function getCategory($categoryId) 
    {
        $this->_category = $this->_categoryFactory->create();
        $this->_category->load($categoryId);        
        return $this->_category;
    }
 
    /**
     * Get category object
     * Using $_categoryRepository
     *
     * @return \Magento\Catalog\Model\Category
     */
    public function getCategoryById($categoryId) 
    {
        return $this->_categoryRepository->get($categoryId);
    }
 
    /**
     * Retrieve current store categories
     *
     * @param bool|string $sorted
     * @param bool $asCollection
     * @param bool $toLoad
     * @return \Magento\Framework\Data\Tree\Node\Collection or
     * \Magento\Catalog\Model\ResourceModel\Category\Collection or array
     */
    public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true) 
    {
        return $this->_categoryHelper->getStoreCategories();
    }
    
    /**
     * Get parent category object
     *
     * @return \Magento\Catalog\Model\Category
     */
    public function getParentCategory($categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getParentCategory();
        } else {
            return $this->getCategory($categoryId)->getParentCategory();        
        }        
    }
    
    /**
     * Get parent category identifier
     *
     * @return int
     */
    public function getParentId($categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getParentId();
        } else {
            return $this->getCategory($categoryId)->getParentId();
        }
    }
    
    /**
     * Get all parent categories ids
     *
     * @return array
     */
    public function getParentIds($categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getParentIds();
        } else {
            return $this->getCategory($categoryId)->getParentIds();
        }        
    }
    
    /**
     * Get all children categories IDs
     *
     * @param boolean $asArray return result as array instead of comma-separated list of IDs
     * @return array|string
     */
    public function getAllChildren($asArray = false, $categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getAllChildren($asArray);
        } else {
            return $this->getCategory($categoryId)->getAllChildren($asArray);
        }
    }
 
    /**
     * Retrieve children ids comma separated
     *
     * @return string
     */
    public function getChildren($categoryId = false)
    {
        if ($this->_category) {
            return $this->_category->getChildren();
        } else {
            return $this->getCategory($categoryId)->getChildren();
        }        
    }    
}
?>

现在,我们在模板文件中获取并打印类别,父类别,子类别和产品计数。

$categoryId = 23; // fetching products in category id 23
 
// Load category by category ID
$category = $block->getCategory($categoryId);
 
// Get Category Level
echo $category->getLevel() . '<br />';
 
// Get total products associated with the category
echo $category->getProductCount() . '<br />';
 
// Get array parent categories of loaded category
$parentCategories = $category->getParentCategories();
 
// Get array of child categories of loaded category
$childrenCategories = $category->getChildrenCategories();
 
// Get single parent category object
$block->getParentCategory();
 
// Get only the category id of single parent category
$block->getParentId();
 
// Get array of all parent category ids
$block->getParentIds();
 
// Get comma-separated children categories ids
$block->getChildren();
 
// Get comma-separated or array of all childrent categories ids
$block->getAllChildren(); // as comma-separated
$block->getAllChildren(true); // as an array
 
// Get nested list of categories and sub-categories along with their product count
$categories = $block->getStoreCategories();
foreach ($categories as $category) {
    echo $category->getName();
    echo ' ( ' . $category->getProductCount() . ' )';
 
    $subCategories = $block->getCategoryById($category->getId());
    foreach ($subCategories as $subCategory) {
        echo $subCategory->getName();
        echo ' ( ' . $subCategory->getProductCount() . ' )';
    }
}

使用对象管理器

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
 
$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');
 
$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$categoryHelper = $objectManager->get('\Magento\Catalog\Helper\Category');
$categoryRepository = $objectManager->get('\Magento\Catalog\Model\CategoryRepository');
 
$categoryId = 21; // YOUR CATEGORY ID
$category = $categoryFactory->create()->load($categoryId);
 
//var_dump($category->getData());
 
$parentCategories = $category->getParentCategories();
$childrenCategories = $category->getChildrenCategories();
 
$storeCategories = $categoryHelper->getStoreCategories();

希望这可以帮助。谢谢。

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论