You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Magento 2如何获取自定义库存源custom source的产品库存数量

实现方案

完全可以实现,你当前使用的是Magento 2旧版单库存架构的接口,仅支持查询默认库存源的库存,要获取自定义库存源的库存需要使用Magento 2.3及以上版本自带的多库存源(MSI)相关接口。

推荐写法(依赖注入,生产环境可用)

首先在你需要调用库存查询的类中通过构造函数注入所需接口,示例代码如下:

// 类的成员变量定义
protected $sourceItemData;
protected $productRepository;

// 构造函数注入
public function __construct(
    \Magento\InventoryApi\Api\GetSourceItemDataBySkuInterface $sourceItemData,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {
    $this->sourceItemData = $sourceItemData;
    $this->productRepository = $productRepository;
}

// 自定义方法获取指定库存源的库存数量
public function getCustomSourceStockQty(int $productId): float
{
    try {
        $product = $this->productRepository->getById($productId);
        // 替换为你后台自定义库存源对应的编码,注意不是源名称,是后台配置的源代码
        $customSourceCode = 'mycustom_source';
        $sourceItem = $this->sourceItemData->execute($product->getSku(), $customSourceCode);
        return $sourceItem ? $sourceItem->getQuantity() : 0;
    } catch (\Exception $e) {
        return 0;
    }
}

快速调试写法(ObjectManager方式,不建议生产环境使用)

如果只是临时调试,可以和你现有写法对齐直接调用ObjectManager,代码如下:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productRepository = $objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$sourceItemData = $objectManager->get(\Magento\InventoryApi\Api\GetSourceItemDataBySkuInterface::class);

$product = $productRepository->getById($product->getId());
// 替换为你后台自定义库存源的实际编码
$customSourceCode = 'mycustom_source';
$sourceItem = $sourceItemData->execute($product->getSku(), $customSourceCode);
$customSourceQty = $sourceItem ? $sourceItem->getQuantity() : 0;

注意事项

  • 你提到的库存源名称为mycustom source,后台对应的源代码一般为下划线分隔的mycustom_source,可以到后台「商店」→「库存」→「库存源」路径下确认对应源的代码字段,查询时必须填源代码而非显示名称。
  • 该方案仅适用于Magento 2.3及以上版本,更低版本没有原生多库存源功能,需要安装第三方多库存管理插件才能实现对应需求。

内容的提问来源于stack exchange,提问作者mariobros

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 01:24:01