문제

I want to get the category name of Parent Category as well as Child Category. For this, I am checking if Category == Parent Category and storing Category name into an array. And If Category is a Sub or Child category I want to store its name as ParentCategoryName / ChildCategoryName.

For example: If Parent Category = Engine and Sub Category = Engine Pump so Category Name = Engine / Engine Pump

Below is my code:

foreach ($categories as $category){
        $thAttribute = $category->getThNewAttribute();

        if(($category->getParentId($category))==2){
            $categoryName[$category->getThNewAttribute()] = $category->getName();
        }else{ 
            $categoryName[$category->getThNewAttribute()] = $category->getParentCategory($category)->getName()."/".$category->getName();
        }
 }

I am getting the correct Category Name for Parent Category but for Sub or Child Category I am getting below error.

No such entity with id = 0

Which step I am doing wrong?

올바른 솔루션이 없습니다

다른 팁

Check below example to list of all subcategories of specific parent category using parent category ID using the repository.

First of all add CategoryRepository in construct:

<?php
    protected $categoryRepository;

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

Now you can use the following way:

<?php
    $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 $childSubcategory->getName();
        }
     }
    }
?>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 magento.stackexchange
scroll top