本文介绍了Magento 2:获取产品库存数量和其他库存信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Magento 2:获取产品库存数量和其他库存信息

Magento 2: Get Product Stock Quantity and Other Stock Information

如何在magento 2中获取产品库存数量和信息

How to get the product stock quantity and information in magento 2

推荐答案

如果我们查看StockItemRepository类,则 get 方法需要参数 $ stockItemId ,而不是$ productId .参考:

If we look at the StockItemRepository class the get method wants parameter $stockItemId, not $productId. Reference:

https://github.com/magento/magento2/blob/develop/app/code/Magento/CatalogInventory/Model/Stock/StockItemRepository.php#L202

我见过很多站点,其库存商品ID与产品ID不相同,我们不应该假定它是相同的ID.

I've seen many sites where stock item id IS NOT the same as product id and we should not assume it's the same ID.

要使其正常工作,您可以改用 \ Magento \ CatalogInventory \ Model \ Stock \ Item 类,并改为通过 product_id 字段加载模型.我也知道 website_id stock_id 字段,但据我所知(尚未),它也存在于M1中.

To get this working you could use \Magento\CatalogInventory\Model\Stock\Item class instead and load the model by product_id field instead. I am also aware of the website_id and stock_id fields, but as far as I know it's not used (yet) and also existed in M1.

它应该看起来像这样(代码未经测试):

It should look something like this (code not tested):

<?php

namespace Vendor\Module\Model;

use \Magento\CatalogInventory\Model\Stock\Item;

class Mymodel
{
    /**
     * @var Item
     */
    protected $stockItem;

    /**
     * Mymodel constructor.
     *
     * @param Item $stockItem
     */
    public function __construct(Item $stockItem)
    {
        $this->stockItem = $stockItem;
    }

    /**
     * Description
     *
     * @param $productModel
     */
    public function getStockQtyByProductId($productModel)
    {
        try {
            $stockItem = $this->stockItem->load($productModel->getId(), 'product_id');

            return $stockItem->getQty();
        } catch (\Exception $e) {
            echo 'Something went wrong and was not handled: ' . $e->getMessage();
            exit;
        }
    }
}

这篇关于Magento 2:获取产品库存数量和其他库存信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 12:02