Magento 2 – 如何获取特定分类的子分类
1. 使用依赖注入
在Block类中添加下面的代码片段。
protected $_categoryFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
array $data = []
)
{
$this->_categoryFactory = $categoryFactory;
parent::__construct($context, $data);
}
/* Get category object */
public function getCategory($categoryId)
{
$category = $this->_categoryFactory->create()->load($categoryId);
return $category;
}
/* Get all children categories IDs */
public function getAllChildren($asArray = false, $categoryId)
{
return $this->getCategory($categoryId)->getAllChildren($asArray);
}
/* Get children ids comma separated */
public function getChildren($categoryId)
{
return $this->getCategory($categoryId)->getChildren();
}
在模板文件中添加以下代码段
$categoryId = 10;
// Load category by category ID
$category = $block->getCategory($categoryId);
echo "<pre>";
print_r($category->getData());
echo "</pre>";
// Get comma-separated children category ids
$childrenCategoryIds = $block->getChildren($categoryId);
echo $childrenCategoryIds;
//Get all children category ids as an array
$allChildrenCategoryIdsArr = $block->getAllChildren(true, $categoryId);
echo "<pre>";
print_r($allChildrenCategoryIdsArr);
echo "</pre>";
//Get all children category ids ids comma-separated
$allChildrenCategoryIds = $block->getAllChildren(false, $categoryId);
echo $allChildrenCategoryIds;
2.使用对象管理器
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$categoryId = 10;
// Load category by category ID
$category = $categoryFactory->create()->load($categoryId);
echo "<pre>";
print_r($category->getData());
echo "</pre>";
// Get comma-separated children category ids
$childrenCategoryIds = $category->getChildren($categoryId);
echo $childrenCategoryIds;
//Get all children category ids as an array
$allChildrenCategoryIdsArr = $category->getAllChildren(true);
echo "<pre>";
print_r($allChildrenCategoryIdsArr);
echo "</pre>";
//Get all children category ids ids comma-separated
$allChildrenCategoryIds = $category->getAllChildren(false);
echo $allChildrenCategoryIds;