Magento2 如何获取商品库存

作为开发人员,您还需要了解产品库存信息,例如缺货订单状态、库存状态、剩余数量、最大数量、最小数量……以及许多其他信息。Magento 2为开发者提供了一些获取产品库存信息的方法。

使用StockItemRepository获取特定产品的库存信息
...
$productId = 620;
/** @var \Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItem */

$stockItem = \Magento\Framework\App\ObjectManager::getInstance()->get(\Magento\CatalogInventory\Model\Stock\StockItemRepository::class)

// Retrieve backorders status
echo $stockItem->getBackorders();

// Get quantity of item remaining in stock
echo "qty: ".$stockItem->getQty();

// Get stock status
echo $stockItem->getIsInStock();

// Retrieve Maximum Qty Allowed in Shopping Cart data wrapper
echo "max sale qty: ".$stockItem->getMaxSaleQty();
...
使用GetSourceItemsDataBySku检索产品多源数量
...
// To retrieve product multi-source quantities, you can use GetSourceItemsDataBySku

/** @var \Magento\InventoryCatalogAdminUi\Model\GetSourceItemsDataBySku $sourceDataBySku */
//use ObjectManager to get \Magento\InventoryCatalogAdminUi\Model\GetSourceItemsDataBySku instance

$sku = "24-MB01"; //sku of product

$sourceDataBySku = \Magento\Framework\App\ObjectManager::getInstance()->get(\Magento\InventoryCatalogAdminUi\Model\GetSourceItemsDataBySku::class);

//load quantities of assigned source
$data = $sourceDataBySku->execute($sku);

// the returned data should be an array including source name, source code, qty of the product in source, source status
// data = array(
//  array(
//      'source_code' => "example",
//      'quantity' => 100,
//      'status' => 1
//      'name' => "Example"
//      'source_status' => true
//)

...
产品存储库用于加载特定产品的所有信息,也可以获取库存
...
   //use product repository to get stock data
  $sku = "883985891715";
/** @var Magento\Catalog\Model\ProductRepository $productRepository */
   $productRepository = \Magento\Framework\App\ObjectManager::getInstance()->get(Magento\Catalog\Model\ProductRepository::class);
   $product = $productRepository->get($sku);
   if ($product){
       echo $product->isSalable(); // Check is product available for sale
       echo $product->isAvailable(); // Check whether the product type or stock allows to purchase the product
       echo $product->getQty(); get quantity of product

   }
...
产品集合对于获取产品列表上的库存信息也很有用。还可以使用股票属性筛选或从集合中获取数据。
...
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection */
$productCollection = \Magento\Framework\App\ObjectManager::getInstance()->get(\Magento\Catalog\Model\ResourceModel\Product\Collection::class);

//use  salable option to filter product in collection
$data =  $productCollection
->addAttributeToFilter("is_saleable", 1)
->setPageSize(5)
->toArray();

...
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容