0

I try to get list category with load(), but I got the error messages on code editor.

phpcs: Ecg.Performance.Loop.ModelLSD: Model LSD method load() detected in loop

This is my code :

public function getCategory()
{
    $product = $this->getCurrentProduct();
    $categories = $product->getCategoryIds();

    foreach ($categories as $category) {
        /** @noinspection PhpDeprecationInspection */
        $cat = $this->category->load($category);
        $catTree = $cat->getName();
    }
    if (!empty($catTree)) {
        return $catTree;
    }
    return true;
}

How to fix this error messages? should I change the method to get category list?

1 Answer 1

0

Instead of loading the full category just to get the name, you can inject Magento\Catalog\Api\CategoryRepositoryInterface via constructor dependency injection and use get() method of this class which will return you the object of Magento\Catalog\Api\Data\CategoryInterface and here you can use getName() method to get the category name.

Using load inside is not Magento recommended practice and also there is no need to load the whole category just to fetch the name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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