I have a function to update the product inventory progrmmatically.below is my function in the helper file.
protected $stockRegistry;
...
public function __construct(
.... //Some code--
\Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry) {
$this->stockRegistry = $stockRegistry;
}
public function updateStockAndPricesByStore($productId,$store_data,$sku)
{
$productFactory = $this->_productFactory->create();
foreach($store_data as $store){
$store_datas = explode("-",$store);
$store_id = $store_datas[0];
$qty = $store_datas[1];
$price = $store_datas[2];
$this->productResourceModel->load($productFactory, $productId);
$productFactory->setStoreId($store_id);
$productFactory->setPrice($price);
$this->productResourceModel->saveAttribute($productFactory, 'price');
$stockItem = $this->stockRegistry->getStockItemBySku($sku, $store_id);
//$stockItem->setStoreId($store_id);
$stockItem->setQty($qty);
echo "Stock Also Updated";
$stockItem->setIsInStock((bool)$qty); // this line
$this->stockRegistry->updateStockItemBySku($sku, $stockItem);
}
}
This is my array i am passing as $store_data
.
Array ( [0] => 1-11-11 [1] => 2-22-22 ) - (store_id - qty - price)
Whenever updating for both stores, last qty updated to both store but price is correctly updating .
How can i update the inventory store wise programatically in Magento 2.