0

I need to update product Qty programmatically, I have my main store where I have my stocks details so I need to update to Magento whenever it's triggered from my Main store or by cron with interval.

Going through I have two ways to implement One through Magento & other with the direct update in DB

I need to reindex & cache clean for DB way, Do I need to reindex & cache clean for Magento Way.

Magento Way

public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository 
    ){
        $this->productRepository = $productRepository;
    }

public function getAssignedProducts($data)
    {
        $stock = 500;
        $product = $this->productRepository->get($sku);
        $product->setStockData(array(
            'qty' => $stock,
            'is_in_stock' => ($stock > 0 ? 1 : 0)
        ));
        $this->productRepository->save($product);
    }

DB Way

catalog_product_entity is to get product details to link catalog_product_entity_decimal & cataloginventory_stock_item

catalog_product_entity_decimal is for price information

cataloginventory_stock_item is for qty information

cataloginventory_stock_status Magento populates itself during reindex, We won’t touch this table.

SELECT row_id, entity_id FROM catalog_product_entity WHERE sku = '123456';

UPDATE cataloginventory_stock_item SET qty = 500, is_in_stock = 1 WHERE product_id = catalog_product_entity.entity_id

UPDATE catalog_product_entity_decimal SET value = 25 WHERE attribute_id = 77 AND row_id = catalog_product_entity.row_id;

attribute_id for the price is 77 this can change check with you system.

Then you need to reindex & cache clean so that Magento populates information for cataloginventory_stock_status

bin/magento indexer:reindex
php/magento cache:clean

Do I need to reindex & cache clean for Magento Way as I do for DB.

Is there any other way that makes the process easy any extension.

Also am I missing anything with DB way.

Your Answer

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

Browse other questions tagged or ask your own question.