2

i try to get getParentCategories for category id

 // 4 is product id 
$product = $this->_productFactory->load(4);
$cats = $product->getCategoryIds();
$category = $this->categoryFactory->create();
         $collection = $category->getResourceCollection();
         $collection->addAttributeToSelect('*')
                    ->addAttributeToFilter('entity_id', $cats)
                    ->addIsActiveFilter()
                    ->load();
//\Magento\Catalog\Model\ResourceModel\Category = $this->category 
foreach ($collection as $cat) {
              $data = $this->category->getParentCategories($cat->getId());
              echo "<pre/>"; print_r($data); exit;
              //$cat->getId();
          } exit;

This code is working in 2.0.7 but not working in 2.1

1

In the Magento 2.1 version, look at vendor/magento/module-catalog/Model/ResourceModel/Category.php. As we can see, the getParentCategories($category) method needs an argument which is an instance of category model.

So, in your case, it should be: $this->category->getParentCategories($cat).

3
  • i try to pass category instance but it's not working. – Pratik Aug 9 '16 at 12:47
  • Your $this->category gets the category collection as well? Try to var_dump some values. – Khoa TruongDinh Aug 9 '16 at 12:53
  • @Pratik Still not working? – Khoa TruongDinh Aug 10 '16 at 15:48
0

It's Working but i think code is not proper way because i loop object see code

$product = $this->_productFactory->load($pid);
        $cats = $product->getCategoryIds();
        if (empty($cats))
            return '';

         $category = $this->categoryFactory->create();
         $collection = $category->getResourceCollection();
            $collection->addAttributeToSelect('*')
                 ->addAttributeToFilter('entity_id', $cats)
                ->addIsActiveFilter()
                ->load();

          $result = '';

        foreach ($collection as $cat) {
            $names = array();

            foreach ($this->category->getParentCategories($cat) as $parent) {
                $names[] = $parent->getName();
            }

            foreach ($names as $key => $label) {
               echo $label;
            }
        } 
3
  • So, using $this->category->getParentCategories($cat) can solve your issue? – Khoa TruongDinh Aug 19 '16 at 12:10
  • Yes but i think this is not good solution. – Pratik Aug 19 '16 at 12:25
  • Yes, you can share me a good solution? I only show you a change in M2.1 version. That causes your issue. – Khoa TruongDinh Aug 19 '16 at 12:31

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.