1

我正在尝试将我的产品从我创建的第一个网站复制到我后来在多商店设置中添加的另外 23 个网站。我有这段代码,我认为应该可以完成这项工作:

$arr_stores = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24);
$store_from = 1;  // first store id

// get observer data and process each imported simple product - my products that need to be copied to     other websites
    $_event = $observer->getEvent();
    $_adapter = $_event->getAdapter();

    foreach($_adapter->getNewSku() as $sku => $value) {

        if($value['type_id'] == 'simple'){
            // load the next product - this loads product correctly
            $_product = Mage::getModel('catalog/product')->setStoreId($store_from)->load($value['entity_id']);

                   // set the websites
            $_product->setWebsiteIds($arr_stores);
            $_product->save();

                    // clear the var
            unset($_product);

        }
    }

但是我收到此错误消息:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`workoutlife`.`catalog_product_website`, CONSTRAINT `FK_CATALOG_PRODUCT_WEBSITE_WEBSITE_ID_CORE_WEBSITE_WEBSITE_ID` FOREIGN KEY (`website_id`) REFERENCES `core_website` (`website_id`) ON DELET)

谁能告诉我为什么这个约束可能会失败?为什么 ON DELET 在那里?我不想删除任何东西。TIA

4

2 回答 2

0

这通常发生在找不到产品时,例如没有这样的 ID/SKU 或参数为 NULL,然后模型返回新产品对象。由于那是空模型,它需要您填写名称、价格等数据。但是从代码的外观来看,您不想这样做。

因此,答案是首先检查$value['entity_id']实际设置为某物且不为 NULL,然后检查该值$_product->getData()$_product->getId()返回某物,如果不是,则意味着无法找到该产品。

于 2014-02-15T00:40:56.813 回答
0

查看 core_website 表。我猜测数组中的一个或多个 id 无效(core_website 中没有匹配的 website_id)。这将违反错误中指定的约束。

catalog_product_website 表的完整约束是:

CONSTRAINT `FK_CATALOG_PRODUCT_WEBSITE_WEBSITE_ID_CORE_WEBSITE_WEBSITE_ID` FOREIGN KEY (`website_id`) REFERENCES `core_website` (`website_id`) ON DELETE CASCADE ON UPDATE CASCADE

ON DELETE CASCADE 意味着如果您从 core_website 表中删除一个条目,catalog_product_website 表中的所有关联条目(具有相同的 website_id)也将被删除。这是一种确保没有剩余无用数据的方法。

您的示例中没有删除任何内容。MySQL 只是喜欢在失败时显示整个约束条目。

于 2012-07-06T04:17:02.927 回答