将产品复制到所有网站 - Magento多商店


Copy products to all websites - Magento multi-store

我正在尝试将我的产品从我创建的第一个网站复制到我稍后在多商店设置中添加的另外 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 在那里?我没有试图删除任何东西。蒂亚

看看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

删除级联意味着如果从core_website表中删除条目,则catalog_product_website表中具有相同website_id的所有关联条目也将被删除。这是一种确保没有无用数据残留的方法。

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

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

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