2014-06-04 3 views
5

Я создаю простые продукты, а затем настраиваемый продукт, а затем сопоставляю простые продукты с настраиваемым продуктом. Когда я запускаю код в первый раз, он работает плавно, создавая все простые продукты, настраиваемый продукт, а также ассоциацию. Но, когда я снова запускаю этот код, он говорит о нарушении ограничений. Идентификатор, который отображается дублирующимся, представляет собой тот же идентификатор продукта, который был создан в последний раз, когда все процессы были в порядке.Нарушение ограничения целостности для ключа 'UNQ_CATALOG_PRODUCT_SUPER_ATTRIBUTE_PRODUCT_ID_ATTRIBUTE_ID'

Мой код следующий.

$product_collection = Mage::getModel('catalog/product') 
    ->getCollection() 
    ->addAttributeToSelect('*'); 

$toinsertId = $product_collection->getLastItem()->getId() + 1; 

$configurable_attribute = "art_print_sizes"; 
$attr_id = 133; 
$simpleProducts = array(); 
$lowestPrice = 999999; 

$attributes = Mage::getModel('catalogsearch/advanced')->getAttributes(); 
$attributeArray = array(); 
foreach ($attributes as $a) { 
    if ($a->getAttributeCode() == 'art_print_sizes') { 
     $count = 0; 
     foreach ($a->getSource()->getAllOptions(false) as $option) { 
      $option_id = $this->getOptionId("art_print_sizes", $option['label']); 
      $sku = 'SK_' . '500' . '_' . strval($count); 

      $sProduct = Mage::getModel('catalog/product'); 
      $sProduct 
       ->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE) 
       ->setWebsiteIds(array(1)) 
       ->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED) 
       ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE) 
       ->setTaxClassId(5) 
       ->setAttributeSetId(9) 
       ->setSku($sku) 
       // $main_product_data is an array created as part of a wider foreach loop, which this code is inside of 
       ->setName($wholedata['name'] . " - " . $option['label']) 
       ->setShortDescription($wholedata['short_description']) 
       ->setDescription($wholedata['description']) 
       ->setPrice(sprintf("%0.2f", $wholedata['attr_val'][$count])) 
       ->setData($configurable_attribute, $option_id); 

      $sProduct->save(); 

      array_push(
       $simpleProducts, 
       array(
        "id" => $sProduct->getId(), 
        "price" => $sProduct->getPrice(), 
        "attr_code" => 'art_print_sizes', 
        "attr_id" => $attr_id, 
        "value" => $option_id, 
        "label" => $option['label'] 
       ) 
      ); 

      $count++; 
     } 
    } 
} 

$cProduct = Mage::getModel('catalog/product'); 
$productData = array(
    'name' => 'Main configurable Tshirt', 
    'sku' => 'tshirt_sku', 
    'description' => 'Clear description about your Tshirt that explains its features', 
    'short_description' => 'One liner', 
    'weight' => 1, 
    'status' => '1', 
    'visibility' => '4', 
    'attribute_set_id' => 9, 
    'type_id' => 'configurable', 
    'price' => 1200, 
    'tax_class_id' => 0 

); 
foreach ($productData as $key => $value) { 
    $cProduct->setData($key, $value); 
} 

$cProduct->setStockData(
    array(
     'manage_stock' => 1, 
     'is_in_stock' => 1, 
     'qty' => 0, 
     'use_config_manage_stock' => 0 
    ) 
); 

$cProductTypeInstance = $cProduct->getTypeInstance(); 
$attribute_ids = array(133); 

$cProductTypeInstance->setUsedProductAttributeIds($attribute_ids); 
$attributes_array = $cProductTypeInstance->getConfigurableAttributesAsArray(); 
foreach ($attributes_array as $key => $attribute_array) { 
    $attributes_array[$key]['use_default'] = 1; 
    $attributes_array[$key]['position'] = 0; 

    if (isset($attribute_array['frontend_label'])) { 
     $attributes_array[$key]['label'] = $attribute_array['frontend_label']; 
    } else { 
     $attributes_array[$key]['label'] = $attribute_array['attribute_code']; 
    } 
} 

$cProduct->setConfigurableAttributesData($attributes_array); 

$dataArray = array(); 
foreach ($simpleProducts as $simpleArray) { 
    $dataArray[$simpleArray['id']] = array(); 
    foreach ($attributes_array as $key => $attrArray) { 
     array_push(
      $dataArray[$simpleArray['id']], 
      array(
       "attribute_id" => $simpleArray['attr_id'][$key], 
       "label" => $simpleArray['label'][$key], 
       "is_percent" => 0, 
       "pricing_value" => $simpleArray['pricing_value'][$key] 
      ) 
     ); 
    } 
} 
$cProduct->setConfigurableProductsData($dataArray); 
$cProduct->setCanSaveConfigurableAttributes(true); 
$cProduct->setCanSaveCustomOptions(true); 
$cProduct->save(); 

Ошибка подобна этой

enter image description here

ID товара 126 уже добавлен в базу данных в предыдущей сессии. И предыдущая сессия прошла удачно, добавив все необходимые продукты.

enter image description here

+0

Пожалуйста, проверьте эту ссылку, это может быть полезно. http://www.magentocommerce.com/boards/m/viewthread/272000/ – Nandakumar

+0

Я вижу, что webkul запущен, попробуйте отключить webkul_marketplace и повторите попытку. Если успех, попросите webkul решить это. –

ответ

0

Magento не позволит обновить конфигурируемые продукты. Так решимостью он просто добавьте ниже код

if($productId){ 
    $resource = Mage::getSingleton('core/resource'); 
    $write = $resource->getConnection('core_write'); 
    $table = $resource->getTableName('catalog/product_super_attribute'); 
    $write->delete($table,"product_id = " . $productId); 
} 

перед тем

$cProduct->setConfigurableAttributesData($attributes_array); 

Так что ваш окончательный код будет

if($productId){ 
    $resource = Mage::getSingleton('core/resource'); 
    $write = $resource->getConnection('core_write'); 
    $table = $resource->getTableName('catalog/product_super_attribute'); 
    $write->delete($table,"product_id = " . $productId); 
} 
$cProduct->setConfigurableAttributesData($attributes_array); 

Примечание: изменение переменной $ PRODUCTID в соответствии с вашим кодом. Вы должны передать идентификатор продукта здесь.

Смежные вопросы