I need to be able to programmatically update product stock in my Cron job. I have an array that contains both the SKU of the product needing updating and the Stock value of that product. How can I select a product by SKU and then update the stock?
Asked
Active
Viewed 7,552 times
1 Answers
6
I'm not sure about your data array which contains the SKU product and Stock value. So, I will use simple data.
We can update product stock via API:
vendor/magento/module-catalog-inventory/Model/StockRegistry.php
vendor/magento/module-catalog/Model/ProductRepository.php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
//Our sample values
$sku = '100098';
$stockValue = 5;
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
$stockRegistry = $objectManager->create('Magento\CatalogInventory\Api\StockRegistryInterface');
//Load product by SKU
$product = $productRepository->get($sku);
//Need to load stock item
$stockItem = $stockRegistry->getStockItem($product->getId());
$stockItem->setData('qty',$stockValue); //set updated quantity
//$stockItem->setData('manage_stock',$stockData['manage_stock']);
//$stockItem->setData('is_in_stock',$stockData['is_in_stock']);
//$stockItem->setData('use_config_notify_stock_qty',1);
$stockRegistry->updateStockItemBySku($sku, $stockItem);
You can quick test our code lines by using playground:
Khoa TruongDinh
- 32,054
- 11
- 88
- 155
This is the line that is throwing the error.
– opqr549 Aug 01 '16 at 15:51STORES > Configuration > CATALOG > Inventory > Product Stock Options > Out-of-Stock Threshold– Khoa TruongDinh Jul 20 '17 at 09:17