Magento 2 - 数量更新后产品丢失缩略图

Magento 2 - Product Loses Thumbnail after quantity update

我不确定为什么使用 Magento 一切都那么困难。我正在尝试以编程方式更新产品数量。

try{
    $product = $this->productRepository->get($sku);
    $product->setStockData( [
        'qty' => $quantity
    ] );

    $this->productRepository->save($product);

} catch (NoSuchEntityException $e) { }

这似乎工作得很好,但是,当我进入管理并查看产品列表时,任何已更新产品的缩略图都丢失了。

如果我进入那个产品并查看它的图片,它们都在那里,缩略图仍然附有 label/role "thumbnail"。

正确的方法是使用 StockRegistryInterface

/**
 * @var StockRegistryInterface
 */
protected $stockRegistry;

/**
 * Inventory constructor.
 * @param StockRegistryInterface $stockRegistry
 */
public function __construct(
    StockRegistryInterface $stockRegistry
)
{
    $this->stockRegistry = $stockRegistry;
}

有了上面的代码,就可以使用如下:

$stockItem = $this->stockRegistry->getStockItemBySku($sku);
$stockItem->setQty($qty);
$this->stockRegistry->updateStockItemBySku($sku, $stockItem);

此代码不会调用您的项目中可能拥有的无关观察者或插件,也不会破坏缩略图