保存现有可配置项时发生完整性约束冲突错误


Integrity constraint violation error when saving an existing Configurable Item

我正在将项目导入Magento作为可配置的项目。当我创建库存项目一切正常,但当项目正在更新它产生这个错误:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '315-315' for key 'UNQ_TEST1_CATALOG_PRODUCT_SUPER_LINK_PRODUCT_ID_PARENT_ID'

我使用的代码块是:

//Try and open for edit.
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $stockCode);            
//Fetch data from XML and update stock item.
$productData = $this->getProductDataArray($stockItem, $stockCategoryList);
$this->saveStockItem($stockItem, $product, 'configurable', $setId, $productData);

//Reopen the stock item to get any changes.
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $stockCode);
//Build a list of existing attributes for this config product so we can check existing attributes etc.
$existingConfigAttributes = $this->getExistingConfigurableAttributes($product);
$configurableProductsData = $this->getConfigurableProductData($product, $existingConfigAttributes);
$configurableAttributesData = $this->getConfigurableAttributeProductData($product, $existingConfigAttributes);
//Set the configurable attribute information
if ($configurableProductsData != null)
    $product->setConfigurableProductsData($configurableProductsData);
if ($configurableAttributesData != null)
    $product->setConfigurableAttributesData($configurableAttributesData);
$product->setCanSaveConfigurableAttributes(1);
$product->save(); 

一切都工作顺利第一次通过和我的可配置项目是按预期工作。但是,如果我再运行一次,它会落在$product->save();上。我假设它试图将此视为一个新的项目,而不是一个现有的,因此试图插入它不应该的地方。

$this->saveStockItem()包含:

$stockCode = (string)$stockItem->STOCK_CODE;
if ($product)
{
    $productId = $product->getId();
}
$mc = new Mage_Catalog_Model_Product_Api();
if ($this->validId($productId))
{
    $mc->update($productId, $productData);
    return $productId;
}
else
{
    return $mc->create($type, $setId, $stockCode, $productData);
}

我知道我可以像这样更新一个项目,但这不会更新我需要添加到可配置项目的额外属性。

更新这些信息的正确方法是什么?

对不起,不能评论(?),所以我必须填写答案字段。

  1. 我不认为Magento试图把产品作为一个新的;按sku加载然后保存是一个正常的过程,在许多情况下对我有效。

我猜,错误消息想说的是,你正试图添加一个项目作为一个已经存在的任何可配置属性的值的子项目;例如,将具有超级属性"size"answers"size=S"的衬衫添加到已经应用了"S"的可配置产品中。所以,也许Magento是把孩子当作新的,而不是可配置的产品。

  1. 错误信息中的键看起来"奇怪"。从你的其他功能中你是否觉得它很眼熟?

  2. 是什么让你不使用超级简单和闪电般的岩浆导入器?; http://sourceforge.net/projects/magmi/)

的问候西蒙。

根据我们的经验,我们必须用product_idstock_id初始化库存项目,否则当我试图保存产品时,我会得到Integrity constraint violation

$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
if($stockItem && !$stockItem->getProductId()) { // CHECK STOCK ITEM IS INITIALISED
    $stockItem->setData('product_id', $productId);
    $stockItem->setData('stock_id', 1);
}
$stockItem->setData('use_config_manage_stock', 0);
$stockItem->setData('manage_stock', 1);
$stockItem->setData('is_in_stock', 1);
$stockItem->setData('qty', 5);
$stockItem->save();
相关文章: