我正在以编程方式创建产品,然后尝试更新其库存数量(XXX(,但产品网格始终显示数量:XXX,默认库存:0。
我使用的是Magento 2.4.4[默认情况下使用多源库存],只有默认来源和默认库存。
以下是我尝试过的:
/** @var MagentoCatalogModelProduct $product */
$product = $this->productFactory->create();
$product
->setTypeId(Type::TYPE_SIMPLE)
->setSku('test');
(...)
/** @var MagentoCatalogApiProductRepositoryInterface $this->productRepository */
$product = $this->productRepository->save($product)
稍后,我尝试使用以下内容更新库存:
1:有效,但已弃用
/** @var MagentoCatalogInventoryModelStockItem $stockItem */
$stockItem = $product->getExtensionAttributes()->getStockItem();
$stockItem
->setIsInStock(true)
->setQty(XXX)
->setStockStatusChangedAuto(true);
$product = $this->productRepository->save($product)
2:有效,但已弃用
$product->setQuantityAndStockStatus(['qty' => XXX, 'is_in_stock' => 1]);
$product = $this->productRepository->save($product)
3:更新产品数量,但不更新其可销售数量。表inventory_stock_1
中填充了零数量,is_salable
=0
/** @var MagentoCatalogInventoryModelStockItem $stockItem */
$stockItem = $product->getExtensionAttributes()->getStockItem();
$stockItem
->setIsInStock(true)
->setQty(XXX)
->setStockStatusChangedAuto(true);
/** @var MagentoInventoryApiApiGetSourceItemsBySkuInterface $this->getSourceItemsBySku */
$stockItems = $this->getSourceItemsBySku->execute($product->getSku());
reset($stockItems)->setQuantity(XXX);
reset($stockItems)->setStatus(SourceItemInterface::STATUS_IN_STOCK);
/** @var MagentoInventoryApiApiSourceItemsSaveInterface $this->sourceItemsSave */
$this->sourceItemsSave->execute($stockItems);
我是否遗漏了任何其他步骤,以便Inventory API方法正常工作?
我的方法是使用源项,您需要首先知道哪些源被分配给产品,然后迭代这些源,看看您试图更新的源是否存在。
按原样创建产品,并确保在继续执行此步骤之前将其保存。
您需要知道您从Magento Admin获得的源代码->商店->库存->来源->代码->{您的源代码:即:"默认"}
/**
* @var MagentoInventoryModelSourceItemCommandGetSourceItemsBySku $getSourceItemsBySku
* @var MagentoInventoryApiApiDataSourceItemInterface $sourceItemInterface
* @var MagentoInventoryApiApiDataSourceItemInterfaceFactory $sourceItemFactory
*
* Create your constructor etc...
**/
$sku = 'test';
$qty = 10;
// CREATE AND SAVE YOUR PRODUCT HERE AS YOU ARE
// Optional
$inventorySaveArray = [];
$sourceItems = $this->getSourceItemsBySku->execute($product->getSku());
foreach ($sourceItems as $item){
if ($item->getSourceCode() === 'my_source_code'){
$sourceItem = $this->sourceItemFactory->create();
$sourceItem->setSourceCode('my_source_code');
$sourceItem->setSku($sku);
$sourceItem->setQuantity((int)$qty);
$sourceItem->setStatus($this->sourceItemInterface::STATUS_IN_STOCK);
$this->sourceItemsSave->execute([$sourceItem]);
break;
}
}
对于多个产品,可以将$sourceItem附加到数组中,并将数组传递给$this->sourceItemsSave->execute($inventorySaveArray(。这使大约200种产品的加工速度加快了几分钟。
在上述代码中,替换:
$this->sourceItemsSave->execute([$sourceItem]);
带有:
array_push($inventorySaveArray, $sourceItem);
然后,在对所有产品进行迭代后,保存数组:
示例:
$this->sourceItemsSave->execute($inventorySaveArray);
适用于Magento 2.4.3、2.4.4和2.4.5