Magento 2 $data[] = $product->getQty(); Returns 0
-
14-04-2021 - |
문제
Trying to get qty of the simple product for csv.
Using $data[] = $product->getQty();
but it returns 0. Looks like it returns default value. How to get the actual quantity of the products?
해결책
To get a simple product stock Quantity, Refer to the below code.
app/code/Vendor/Module/Block/StockData.php
<?php
namespace Vendor\Module\Block;
class StockData extends \Magento\Framework\View\Element\Template
{
protected $_stockItemRepository;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository,
array $data = []
)
{
$this->_stockItemRepository = $stockItemRepository;
parent::__construct($context, $data);
}
public function getStockItem($productId)
{
return $this->_stockItemRepository->get($productId);
}
}
?>
Now you can get quantity in your template file like this.
$productStockData = $block->getStockItem($product->getId());
echo $productStockData->getQty();
Or you can use objectManager (Not Preferable)
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$stockItemRepository = $objectManager->get('\Magento\CatalogInventory\Model\Stock\StockItemRepository');
$productStockData = $stockItemRepository->get($product->getId());
echo $productStockData->getQty();
?>
다른 팁
This worked for me
echo $_product->getExtensionAttributes()->getStockItem()->getQty();
제휴하지 않습니다 magento.stackexchange