0

I am trying to get the SKU of a product, but I just can't find out how to correctly use \Magento\Catalog\Api\ProductRepositoryInterface. It works when i use the getList() method, but getById() leads to a timeout (see the following code):

class LiveItem extends \Magento\CatalogInventory\Model\Stock\Item
{
    public function __construct(
        ...
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        ... more DI
        )
    {
        $this->productRepository = $productRepository;
        ...
    }

    public function getQty()
    {
        //this works:
        foreach (($this->productRepository->getList(
            $this->searchCriteriaBuilder->create()
        )->getItems()) as $item)
        {
            var_dump($item->getId()); //$item->getSku() works as well
        }

        //but this doesnt (4696 definitely exists according to the var_dump output above):
        print_r($this->productRepository->getById(4696));
    }
}

Can someone help me in finding out what's going on here? I'm on Magento 2.2.1

Is there another way to get the product's SKU?

0

getById return object of \Magento\Catalog\Api\Data\ProductInterface.

Try this code:

/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $this->productRepository->getById(4696);
var_dump($product->getId());

Write me if you have any issues.

  • Thanks Evgeny, this works! I assume I can't var_dump the whole $product because it consumes to much memory - am I right? – bayer Nov 19 '17 at 10:45
  • Yes, of course. You are right :) – Evgeny Levinsky Nov 19 '17 at 10:48

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.