1

You know how you've got;

$tempProduct->setData('price', 9.99);
$tempProduct->getResource()->saveAttribute($tempProduct,'price');

I want to do the same, except for stock;

$stockData = $tempProduct->getStockData();
$stockData['qty'] = 0;
$stockData['is_in_stock'] = 0;
$stockData['manage_stock'] = 1;
$stockData['use_config_manage_stock'] = 0;
$tempProduct->setStockData($stockData);
$tempProduct->getResource()->saveAttribute($tempProduct,'quantity_and_stock_status');

This doesn't work, it breaks at

$tempProduct->getResource()->saveAttribute($tempProduct,'quantity_and_stock_status');

Note: I do not want to use $product-save() / $tempProduct->save()

What can I do?

2
  • You want to update by API or? Sep 2 '19 at 4:51
  • API Object Manager / Object Model, ye Sep 2 '19 at 5:04
0

Try to use this below code :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$sku = '24-MB01';
$stockValue = 5;
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
$stockRegistry = $objectManager->create('Magento\CatalogInventory\Api\StockRegistryInterface');
$product = $productRepository->get($sku); // Load Product by SKU
$stockItem = $stockRegistry->getStockItem($product->getId()); // Load Stock Item
$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);

Note : Object Manager direct use is not good practise. You should follow construct method.

0

use this script it will help you out.

protected $stockRegistry;

public function __construct(
    ...
    \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
    ...
)
{
    $this->stockRegistry = $stockRegistry;
}

Now use above instances and do update stock like this:

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

Hope this will help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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