1

im new bie about magento and im facing an issue: For example: in my system have Category 1(id=1) -> category 11(id=2) -> category111(id=3), category 112(id=4) , category 113(id=5). So i finding the solution: if i have id of category 11(2) how can i get all id related with this category. The expected result be like:[1,2,3,4,5]. if category111 or the other (level 3 ) have subcategory it also appear in the result. Thanks for helping me!

2 Answers 2

0

You can use below code to get all subcategories of parent category using category id

First of all add CategoryRepository in construct:

<?php
    protected $categoryRepository;
    
    public function __construct(
        \Magento\Catalog\Model\CategoryRepository $categoryRepository
    ) {
        $this->categoryRepository = $categoryRepository;
    }

    $categoryId = [YOUR_CATEGORY_ID];
    $category = $this->categoryRepository->get($categoryId);
    $subCategories = $category->getChildrenCategories();
    foreach($subCategories as $subCategory) {
        echo $subCategory->getName();

        /* For Sub Categories */
        if($subcategorie->hasChildren()) {
            $childCategoryObj = $this->categoryRepository->get($subCategory->getId());
            $childSubcategories = $childCategoryObj->getChildrenCategories();
            foreach($childSubcategories as $childSubcategory) {
                 echo 'Sub Category' . $childSubcategory->getName();
            }
        }

        /* For parent categories */
        if ($category->getParentIds) {
           $parentCategories = $category->getParentIds();
           foreach($parentCategories as $parentCategory) {
             echo 'Parent Category' . $parentCategory->getName();
           }
        }
    }
?>
0

If having the issue in getting parents and children categories from a category in magento2 then no need to worry about this.Here we will see how to get parents and children categories from a category in Magento2.

<?php
protected $categoryFactory;

public function __construct(
    \Magento\Catalog\Model\CategoryFactory $categoryFactory
) {
    $this->categoryFactory = $categoryFactory;
}

public function getChildrenCategoriesById($categoryId)
{
    $category = $categoryFactory->create()->load($categoryId);
    $parentCategories = $category->getParentCategories();
    $parentCategoryIds = [];
    $childIds = [];
    foreach ($parentCategories as $parentCategory) {
        $parentCategoryIds[$parentCategory->getId()] = $parentCategory->getName();
    }
    $childrenCategories = $category->getChildrenCategories();
    foreach ($childrenCategories as $key => $category){
        $childIds[$category->getId()] = $category->getName();
    }
}

?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.