Magento 2.1 Cron Job – How to Update Product Stock

cronmagento-2.1magento2skustock

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?

Best Answer

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:

How can I bootstrap Magento 2 in a test.php script?

http://www.boolfly.com/magento-2-playground/

Related Topic