1

via ProductRepository:

$product = $this->productRepository->get($product['sku']);
$stockItem = $this->stockRegistry->getStockItem($product->getId());

$stockItem->setIsInStock(true);
$this->stockRegistry->updateStockItemBySku($product->getSku(), $stockItem);
$product->setTypeId('configurable');
$this->productRepository->save($product);

StockItem is not updated!! Product is saved. But Stock is not (or rolled back). If comment the last line in code above (product saving) - stock will updated ok.

via Model \Magento\Catalog\Model\Product:

$productModel = $this->productFactory->create();
$product = $productModel->loadByAttribute('sku', $product['sku']);
$stockItem = $this->stockRegistry->getStockItem($product->getId());

$stockItem->setIsInStock(true);
$this->stockRegistry->updateStockItemBySku($product->getSku(), $stockItem);
$product->setTypeId('configurable');
$product->save($product);

Both - StockItem and Product updated!

How to update stock and update product in Magento way?

1 Answer 1

2

It happens because product loaded from Repository contains deprecated data:

  ["quantity_and_stock_status"]=>
  array(2) {
    ["is_in_stock"]=>
    bool(false)
    ["qty"]=>
    float(0)
  }

That's why productRepository->save($product) overwrites previously saved stock item.

So correct code is:

$product = $this->productRepository->get($product['sku']);

//Magento way
$stockItem = $this->stockRegistry->getStockItem($product->getId());
$stockItem->setIsInStock(true);
$this->stockRegistry->updateStockItemBySku($product->getSku(), $stockItem);

$product->setTypeId('configurable');

//Deprecated workaround
$product->setQuantityAndStockStatus(1);
$this->productRepository->save($product);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.