我正在开发一个 magento 模块,其中以编程方式创建可配置和简单的产品。以下代码创建了可配置和简单的产品,但不关联它们:
$sProduct = Mage::getModel('catalog/product');
$sProduct
->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE)
->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE)
->setSku($sku)
->setName($name)
->setPrice($price)
->setAttributeSetId($set_id) //id of set which contains size_range_c attribute
->setData("size_range_c", $option_id)
->setData("color", $colorId) //another attribute in set but not required
->setDescription($description)
->setShortDescription($short_description)
->setTaxClassId(0);
$sProduct->setStockData(array(
'is_in_stock' => 1,
'qty' => $qty
));
$sProduct->save();
$cProduct = Mage::getModel('catalog/product');
$cProduct->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->setSku($csku)
->setName($cname)
->setPrice($price)
->setAttributeSetId($set_id) //same set is used for both configurable and simple product
->setUrlKey($url)
->setDescription($description)
->setShortDescription($short_description)
->setTaxClassId(0);
$all_child_products = array();
$all_child_products[$sProduct->getId()] = array(
$sv = array('attribute_id' => $attrId, //attrbute id of size_range_c
'label' => $attr_name, //option name
'value_index' => $option_id, //option_id
'pricing_value' => 0,
'is_percent' => 0)
);
$size_values = array();
$size_values[] = $sv;
$_attributes = Mage::getResourceModel('eav/entity_attribute_collection')
->addFieldToFilter('attribute_code', 'size_range_c');
$attribute = $_attributes->getFirstItem(); //get data for size_range_c
$cProduct->setConfigurableProductsData($all_child_products);
$cProduct->setConfigurableAttributesData(array(
array_merge($attribute->getData(), array('label' => '', 'values' => $size_values))
));
$cProduct->setCanSaveConfigurableAttributes(true);
$cProduct->setCanSaveCustomOptions(true);
$cProduct->save();
基本上,我为每种颜色创建一个可配置的产品,然后为该颜色的每种尺寸创建一个简单的产品,然后将它们关联起来。可配置产品和简单产品都需要 size_range_c 属性。当我从管理面板查看这些产品时,一切似乎都很好。我什至尝试手动将简单产品与可配置产品相关联,但以编程方式创建的产品不会出现在相关产品部分。