简体   繁体   English

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

[英]Magento 2 - Product Loses Thumbnail after quantity update

I'm not sure why everything is so difficult with Magento. 我不确定Magento为何会如此困难。 I am trying to update product quantities programatically. 我正在尝试以编程方式更新产品数量。

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

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

} catch (NoSuchEntityException $e) { }

This seems to work just fine, however, when I go into the admin and look at the products list, the thumbnails are missing for any product that has been updated. 这似乎工作得很好,但是,当我进入管理员页面并查看产品列表时,所有已更新产品的缩略图都将丢失。

If I go into that product and look at its images they are all there and the thumbnail image still has the label/role "thumbnail" attached. 如果我进入该产品并查看其图像,它们就全部存在,并且缩略图图像上仍然贴有标签/角色“缩略图”。

The correct way to do this is by using the StockRegistryInterface 正确的方法是使用StockRegistryInterface

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

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

With the above code, you can use the following: 通过上面的代码,您可以使用以下代码:

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

This code will not call unrelated observers or plugins that you may have on your project and it will not break the thumbnail 此代码不会调用您项目中可能没有的无关的观察者或插件,并且不会破坏缩略图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM