So, I'm trying to update product quantities programmatically. On a standard magento install, it works flawlessly, but on the actual magento shop I'm developing it for, it fails with a SQLSTATE[23000]: Integrity constraint violation
.
It happens when I save the alterations I made on the product. The relevant bit of code,
// Check if the product exists
$id = Mage::getModel('catalog/product')->getIdBySku($sku);
if ($id) {
$product = Mage::getModel('catalog/product')->load($sku, 'sku');
$stockItem = $product->getStockItem();
$totalStock = $stockItem->getData('qty') + $qty;
$stockItem->setData('qty', $totalStock)
->setData('is_in_stock', $totalStock > 0 ? 1 : 0);
try {
$stockItem->save();
} catch (Exception $e) {
echo $e->getMessage();
}
}
which returns the exception,
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a
child row: a foreign key constraint fails
(`staging_shop`.`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`) O)
I'm a bit at a loss here, and googling hasn't really helped at all. Might this be some extension or something that is messing with me, or is the database corrupt? Any help, even the smallest, is appreciated!
UPDATE: Solution below
Thanks to @boomer, I managed to get it working. Just for future reference (and fellow googlers), the following code is what works (at least with magento 1.8.x),
// Check if the product exists
if (Mage::getModel('catalog/product')->getIdBySku($sku)) {
// Load the product stock object
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct(
Mage::getModel('catalog/product')->loadByAttribute('sku', $sku)
);
// Add to the existing quantity of the product
$stockItem->addQty($qty)->save();
}