magento2magento-2.3

Get custom stock product quantity


I use this code to retrieve product quantity by given id

$stockItem = $objectManager->get('\Magento\CatalogInventory\Model\Stock\StockItemRepository');
$productId =  10858;
$productStock = $stockItem->get($productId);
$productStock->getData();

This code work and return this results

array (
  'item_id' => '10858',
  'product_id' => '10962',
  'stock_id' => '1',
  'qty' => '0.0000',
  'min_qty' => '0.0000',
  ...
)

But I need to retrieve information by stock_id = 2 instead of default stock (id: 1) There's a way to do this, using this code?


Solution

  • $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    
    $productId = 1;
    
    $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
                                        $product_qty = $StockState->getStockQty($productId);