0

I have the following code to create a product, but when I try to do it it throws me this exception:

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento`.`catalog_product_entity`, CONSTRAINT `FK_CAT_PRD_ENTT_ATTR_SET_ID_EAV_ATTR_SET_ATTR_SET_ID` FOREIGN KEY (`attribute_set_id`) REFERENCES `eav_attribute_set` (`attribute_set_id`) ON DE), query was: INSERT INTO `catalog_product_entity` (`entity_type_id`, `sku`, `created_at`, `updated_at`) VALUES (?, ?, '2017-09-11 18:54:40', '2017-09-11 18:54:40')

Here is my code:

$single = $return['response']['diffgrdiffgram']['NewDataSet']['Produtos']['0'];
$category = Mage::getModel('catalog/category');    
$products = Mage::getModel('catalog/product');


$attr = Mage::getModel('novapc_allnations/attr')->load(1, 'entity_id');

$attr = array(
$attr->getData('fabricante'),
$attr->getData('part_number'),
$attr->getData('ean'),
$attr->getData('garantia'),
$attr->getData('peso'),
$attr->getData('preco_revenda'),
$attr->getData('preco_sem_st'),
$attr->getData('ncm'),
$attr->getData('largura'),
$attr->getData('altura'),
$attr->getData('profundidade'),
$attr->getData('subst_tributaria'),
$attr->getData('origem_produto'));

$control = Mage::getStoreConfig('allnations/general/id_allnations', 
Mage::app()->getStore());
if ($control != 'sku' and $control == 'other') {
    $control = 
Mage::getStoreConfig('allnations/general/id_allnations_other', Mage::app()->getStore());
}

    $products->setName($single['DESCRICAO'])
    ->setDescription($single['DESCRTEC'])
    ->setShortDescription($single['DESCRICAO'])
    ->setAvailable($single['DISPONIVEL'])
    ->setStatus($single['ATIVO'])
    ->setSku($single['CODIGO'])
    ->setWebsiteIds(array(1))
    #->setAttributeSetId(9)
    ->setTypeId('simple')
    ->setCreatedAt(strtotime('now'))
    ->setTaxClassId(4)
    ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
    ->setPrice($single['PRECOREVENDA'])
    ->setWeight($single['PESOKG'])
    ->setStockData(array(
        'use_config_manage_stock' => 0,
        'manage_stock' => 1,
        'min_sale_qty' => 1,
        'max_sale_qty' => 5,
        'is_in_stock'  => $single['DISPONIVEL'],
        'qty'          => $single['ESTOQUEDISPONIVEL']
    ));

$products->setData(array(
    $control    => $single['CODIGO'],
    $attr['0']  => $single['FABRICANTE'],
    $attr['1']  => $single['PARTNUMBER'],
    $attr['2']  => $single['EAN'],
    $attr['3']  => $single['GARANTIA'],
    $attr['4']  => $single['PESOKG'],
    $attr['6']  => $single['PRECOSEMST'],
    $attr['7']  => $single['NCM'],
    $attr['8']  => $single['LARGURA'],
    $attr['9']  => $single['ALTURA'],
    $attr['10'] => $single['PROFUNDIDADE'],
    $attr['11'] => $single['SUBSTTRIBUTARIA'],
    $attr['12'] => $single['ORIGEMPRODUTO']
));

$products->setStoreId(2);

# Pega a CATEGORIA e a SUBCATEGORIA
$mainCat = $single['CATEGORIA'];
$subCat = $single['SUBCATEGORIA'];

# Faz uma checagem para ver se a categoria e a sub-categoria são iguais,
# se forem, adiciona somente na principal, se não forem, adiciona nas duas
if ($mainCat == $subCat) {
    $filter = $category->getCollection()
        ->addAttributeToFilter('name', ['eq' => $mainCat])
        ->addAttributeToSelect('*');

    $filter = $filter->getFirstItem();

    $products->setCategoryIds($filter->getId());
} else {
    $filter = $category->getCollection()
       ->addAttributeToFilter('name', ['eq' => $mainCat])
       ->addAttributeToSelect('*');

      $filter = $filter->getFirstItem()
      ->getId();

        $subFilter = $category->getCollection()
            ->addAttributeToFilter('name', ['eq' => $subCat])
            ->addAttributeToSelect('*');

        $subFilter = $subFilter->getFirstItem()->getId();

        $products->setCategoryIds(array($filter, $subFilter));
}
0

I see this method is commented on your code:

->setAttributeSetId(9)

The attribute_set_id is required for product creation. Also, check if the attribute_set_id you specified exists in eav_attribute_set table.

  • Uncommented it and stills throws same error with ID 1. I do have it in eav_attribute_set, but, for some reason, the attribute sets from id 1 to 8 are all named Default, the 9 is missing and from 10 onwards are customs. Dunno if that could be it – Stordon Sep 12 '17 at 11:51
0

You have forgotten :

->setStoreId(1)
->setAttributeSetId(9) //ID of a attribute set named 'default'
  • I did not. I have ->setStoreId(1) after I set my $attr data. and AttributeSetId is commented, but I uncommented it and it still throws same error – Stordon Sep 12 '17 at 11:48
0

Ok... I don't know why, but changing this:

$products->setAttributeSetId(4);

to this:

$products->setData([
    'attribute_set_id' => 4
]);

worked.

Of course, I soft-coded it:

'attribute_set_id' => $products->getDefaultAttributeSetId(),

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.