0

I'm trying to update Stock Qty for a Magento Product. I either create a new product or update an existing product with the same call. I do it like this:

    if ($product->getQty() !== ($productData['inventory'] ?? 0)) {
        $stockItem = $product->getStockItem();
        $stockItem->assignProduct($product)->setData([
            'qty' => $productData['inventory'] ?? 0,
            'is_in_stock' => 1,
            'use_config_manage_stock' => 1,
            'manage_stock' => 1,
        ]);
        $product->setStockItem($stockItem);
        $product->setStockData([
            'qty' => $productData['inventory'] ?? 0,
            'is_in_stock' => 1,
            'use_config_manage_stock' => 1,
            'manage_stock' => 1,
        ]);
    }

Yet, when I try to issue save() it keeps telling me either:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1234567-1' for key 'UNQ_CATALOGINVENTORY_STOCK_ITEM_PRODUCT_ID_STOCK_ID', query was: INSERT INTO cataloginventory_stock_item (product_id, stock_id, qty, is_in_stock, low_stock_date, manage_stock, use_config_manage_stock, stock_status_changed_auto) VALUES (?, ?, ?, ?, ?, ?, ?, ?) at /var/www/html/htdocs/lib/Zend/Db/Statement/Pdo.php on 235

or

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (magento.cataloginventory_stock_item, CONSTRAINT FK_CATINV_STOCK_ITEM_PRD_ID_CAT_PRD_ENTT_ENTT_ID FOREIGN KEY (product_id) REFERENCES catalog_product_entity (entity_id) ON DELETE CA), query was: INSERT INTO cataloginventory_stock_item (qty, is_in_stock, manage_stock, use_config_manage_stock) VALUES (?, ?, ?, ?) at /var/www/html/htdocs/lib/Zend/Db/Statement/Pdo.php on 23

5

What am I doing wrong here?

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.