Нарушение ограничения целостности magento во время создания/обновления продукта

В настоящее время я пытаюсь интегрировать magento в систему ERP, используя самостоятельно написанное промежуточное программное обеспечение. Я получаю это сообщение:

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` (`a)

Я действительно не знаю, где проблема. Результат Object of a Product get и Product write выглядит одинаково. Я уже проверил в Интернете помощь, но не смог найти для нее решения. Я также не знаю, где искать, потому что сообщение сверху — единственное, что я получаю.

Любая помощь приветствуется.


Ну, сам код разбит на несколько разделов.

но я постараюсь показать как можно больше

 $this->product = Mage::getModel('catalog/product')->loadByAttribute('sku',$this->handler['art_nr']);
        if($this->product===false || $this->product->getId()<1){
            $this->product = Mage::getModel('catalog/product');
            $this->product->setSku($this->handler['art_nr']);
            $this->newProduct = true;
        }
        $this->product->setStatus($this->shoparticle['products_status']);
        $this->product->setName($this->handler['art_name']);
        $categories = array();
        if(!$this->isNewProduct()){
            $categories = $this->product->getCategoryIds();
        }
        $categories = $this->handler['all_categories'];
        $this->product->setCategoryIds($categories);
        $crosssellingSet    = array();
        $upsellingSet       = array();
        $relatedSet         = array();
        if(is_array($this->handler['xselling']) && count($this->handler['xselling'])>0){
            foreach($this->handler['xselling'] as $valueSet){
                $product = Mage::getModel('catalog/product')->loadBySku($valueSet['art_nr']);
                if((int)$valueSet['group']===1){
                    $crossselling[$product->getId()] = array('position'=>$valueSet['sort_oder']);
                }else if((int)$valueSet['group']===2){
                    $upsellingSet[$product->getId()] = array('position'=>$valueSet['sort_oder']);
                }else if((int)$valueSet['group']===3){
                    $relatedSet[$product->getId()] = array('position'=>$valueSet['sort_oder']);
                }
            }
        }
        $this->product->setCrossSellProductsData($crosssellingSet);
        $this->product->setUpsellingProductsData($upsellingSet);
        $this->product->setRelatedProductsData($relatedSet);
        $importDir = Mage::getBaseDir('media') . DS . 'import' . DS;
        //check if exists and add .htaccess file for protection
        if(!is_dir($importDir)){
            @mkdir($importDir,0775,true);
            @chmod($importDir,0775);
        }
        if(!is_dir($importDir)){
            throw new Connector_Model_Exception_Error('Could not create import Directory!');
        }
        if(!file_exists($importDir.'.htaccess')){
            file_put_contents($importDir.'.htaccess','Order deny,allow'."\n".'Deny from all'."\n");
        }
        //clean direcotry
        $dir = dir($importDir);
        while(($e=$dir->read())!==false){
            if(strpos($e,'.jpg')||strpos($e,'.png')||strpos($e,'.jepg')||strpos($e,'.gif')||strpos($e,'.tif')){
                @unlink($importDir.$e);
            }
        }
        //write images into directory
        //and run Import
        foreach($this->handler['images'] as $image){
            file_put_contents($importDir.$image['image_name'],$image['image']);
            $this->product->addImageToMediaGallery($importDir.$image['image_name'], array('image', 'small_image', 'thumbnail'), false, false);
        }
        $groups = Mage::getModel('customer/group')->getCollection()->getAllIds();
        if((float)$this->handler['Bpreis'] > 0.00){
            $this->product->setPrice((float)$this->handler['Bpreis']);
        }
        if((float)$this->handler['art']['products_pprices'] > 0.00){
            $this->product->setMsrp((float)$this->handler['art']['products_pprices']);
        }
        //preapre the price data for ranges
        $groupsets = array();
        if(count($this->handler['PGROUP'])){
            foreach($this->handler['PGROUP'] as $group){
                if(in_array(((int)$group['gruppe']-250),$groups)){
                    $groupsets[((int)$group['gruppe']-250)][(float)$group['marge']] = (float)$group['PGPRICE'];
                }
            }
        }
        //Now run ageanst groupsets to set price range etc
        $storeid = Mage::app()->getStore()->getWebsiteId();
        foreach($groupsets as $groupid=>$rangeset){
            if(count($rangeset)>0){
                foreach($rangeset as $key=>$value){
                    if(count($rangeset)===1 && $key === (float)0){
                        $this->product->setData(
                            'group_price',
                            array(
                                'website_id'=>$storeid,
                                'cust_group'=>$groupid,
                                'price'=>$value,
                            )
                        );
                    }else{
                        $this->product->setData(
                            'tier_price',array(
                                'website_id'=>$storeid,
                                'cust_group'=>$groupid,
                                'price'=>$value,
                                'price_qty'=>$key
                            )
                        );
                    }
                }
            }
        }
        Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
        if($this->isNewProduct()){
            $this->product->setCreatedAt(strtotime('now'));
        }
        $this->product->save();

person Chris West    schedule 08.01.2014    source источник


Ответы (2)


Ошибка говорит вам точно, в чем проблема. Вы пытаетесь сохранить продукт с неверным идентификатором набора атрибутов. Это означает, что идентификатор набора атрибутов, который вы установили или не установили в этом случае, отсутствует в таблице eav_attribute_set. Я думаю, это потому, что если вы создаете новый продукт, вы не устанавливаете его. Если вы обновляете существующий, вам не нужно его устанавливать.

if($this->product===false || $this->product->getId()<1){
    $this->product = Mage::getModel('catalog/product');
    $this->product->setSku($this->handler['art_nr']);
    // Set Attribute Set. Should be numeric for simple, bundle, configurable, grouped etc
    $this->product->setAttributeSetId($this->handler['art_attribute_set_id']); 
    $this->newProduct = true;
}
person Ashley Swatton    schedule 10.01.2014
comment
спасибо очень помогло. Не видел этого в моем туториале ^^ - person Chris West; 10.01.2014
comment
Нет проблем. Обратите внимание, что magento использует Innodb, поэтому все внешние ключи проверяются для обеспечения целостности данных. Если вы получаете больше подобных ошибок, проверьте значение, используемое в качестве внешнего ключа, и убедитесь, что оно находится в базе данных и является действительным. - person Ashley Swatton; 10.01.2014
comment
Я буду внимательно следить за этим. Большое спасибо. - person Chris West; 13.01.2014

Пожалуйста, проверьте, используете ли вы правильный идентификатор набора атрибутов с вашим кодом. Пожалуйста, поделитесь кодом, где вы написали код для обновления/сохранения продукта.

person Saurabh    schedule 08.01.2014