“Call to a member function getIsInStock() on null” with getExtensionAttributes()->getStockItem()
-
01-10-2020 - |
Question
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?
Solution
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.
OTHER TIPS
If you have access to the productRepository you can do this:
$this->_productRepository->getById($product->getId())->getExtensionAttributes()->getStockItem()->getIsInStock();