How to get all products with Qty in magento2
-
16-02-2021 - |
Question
I am trying to get all products
with it's stock qty
in magento2.
please let me know if anybody have solution.
La solution
you can get all products
with qty
using below code
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
$collection = $productCollection->create()
->addAttributeToSelect('*')
->load();
foreach ($collection as $product){
echo $StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
echo $product->getName();
}
?>
Autres conseils
Instead of using Object Manager, use dependency structure for good practise.
/**
* @var \Magento\Framework\View\Result\PageFactory
*/
protected $productFactory;
public function __construct(
.....
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
.....
)
{
.....
$this->productFactory = $productFactory;
.....
}
public function execute()
{
$product = $this->productFactory->create();
$product->addAttributeToSelect('*')->setFlag('has_stock_status_filter', true);
$product = $product->joinField('qty',
'cataloginventory_stock_item',
'qty',
'product_id=entity_id',
'{{table}}.stock_id=1',
'left'
)->joinTable('cataloginventory_stock_item', 'product_id = entity_id', ['stock_status' => 'is_in_stock'])
->addAttributeToSelect('stock_status')
->addAttributeToSort('entity_id', 'DESC')
->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->load();
return $product;
}
Collection stock item from Resource Model
$resource = $objectManager->create('Magento\CatalogInventory\Model\ResourceModel\Stock\Item');
$select = $resource->getConnection()->select()->from($resource->getMainTable());
$stockItems = $resource->getConnection()->fetchAll($select);
foreach($stockItems as $_item){
var_dump($_item->getData());
}
if you have product object then just use following:
var_dump($_product->getExtensionAttributes()->getStockItem()->getData());
I hope this will help
Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange