This works for me:
$item = ['qty' => 11]; // For example
$product->setStockData(['qty' => $item['qty'], 'is_in_stock' => $item['qty'] > 0]);
$product->save();
Edit:
This is no longer the correct way to handle this, because $product->save()
is deprecated since Magento 2.1. The correct way to do this is by using the StockRegistryInterface
:
/**
* @var StockRegistryInterface
*/
protected $stockRegistry;
/**
* Inventory constructor.
* @param StockRegistryInterface $stockRegistry
*/
public function __construct(
StockRegistryInterface $stockRegistry
)
{
$this->stockRegistry = $stockRegistry;
parent::__construct();
}
With the above code, you can use the following:
$sku = 'ABC123';
$qty = 10;
$stockItem = $this->stockRegistry->getStockItemBySku($sku);
$stockItem->setQty($qty);
$this->stockRegistry->updateStockItemBySku($sku, $stockItem);
Use ManagersManagers as much as possible. Keep your modules decoupled from each other.
It's The Magento Way™