0

I try to access stock data for a product, using

$product->getExtensionAttributes()->getStockItem()->getIsInStock()

and receive the following error on this line

PHP Fatal error: Call to a member function getIsInStock() on null.

Obviously the stock_item extension attribute was not loaded. $product comes from the product repository and has been loaded with $productRepository->getList().

How can I get products with stock information from the product repository?

0

If you have access to the productRepository you can do this:

$this->_productRepository->getById($product->getId())->getExtensionAttributes()->getStockItem()->getIsInStock();

  • But this will trigger another full product load, right? The repository methods are slow enough already, triggering the classic "load in a a loop" is not an option for me. – Fabian Schmengler Aug 2 '16 at 21:00
  • 1
    Correct. You can't call isInStock() on the items, since they'll always return 1, even if they're not in stock and you also can't use getStockData() since that'll return NULL. As far as I know stock data isn't included in the product list items. – Ruud N. Aug 2 '16 at 21:10
  • Thanks, I'll probably resort to collections again for more flexibility – Fabian Schmengler Aug 2 '16 at 21:13
  • Alternatively you can use the \Magento\CatalogInventory\Api\StockItemRepositoryInterface to just load the stock item seperately, like this: $this->_stockItemRepository->get($product->getQuantityAndStockStatus())->getIsInStock() – Ruud N. Aug 2 '16 at 21:51
  • 3
    where i can find method getQuantityAndStockStatus define? – mrtuvn Aug 4 '16 at 3:31
0

Apparently this is not possible in a reasonable way as of Magento 2.1

You can use the stock registry and pass each item of the result to Magento\CatalogInventory\Helper\Stock::assignStatusToProduct().

But this results in a single database query for each product. In my tests with 2000 products, this takes three times longer than loading the collection directly with Magento\CatalogInventory\Model\ResourceModel\Stock\Status::addStockDataToCollection()

To optimize the stock registry, one would have to add a method to fetch multiple stock items at once and assign them to an array of products.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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