Question

I have product object & i get category ids using

$category_id = $product->getCategoryIds();

I need the collection for the category ids which i get in $category_id What will be the best & optimized way to get it in (block or helper or model) ?

Thanks

Was it helpful?

Solution

You can use the category collection factory for getting the category.

public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
    ) {
            $this->_categoryCollectionFactory = $categoryCollectionFactory;
            parent::__construct($context, $data);
    }

public function getCategoryCollection()
    {
        $categoryIds = $product->getCategoryIds();

        $collection = $this->_categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->addAttributeToFilter('entity_id', $categoryIds);
    }

Let me know still if you face any queries.

Thanks

OTHER TIPS

1)Create a Block and add following code:

<?php
namespace vendor\Category\Block;

class Category extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository,
        array $data = []
    ) {
        $this->categoryRepository = $categoryRepository;
        parent::__construct($context, $data);
    }

    /* $categoryId as category id */
    public function getCategoryById($categoryId){
        try {
            return $category = $this->categoryRepository->get($categoryId);
        } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
            return ['response' => 'Category Not Found'];
        }
    }
}

2)Create custom template and add following code:

$categoryId = 5; // category id
$getCategory = $block->getCategoryById($categoryId);
echo $getCategory->getName();echo "<br>";
echo $getCategory->getUrlKey();echo "<br>";
echo $getCategory->getIsActive();echo "<br>";
echo "<pre>";print_r($getCategory->getData());
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top