Magento: Adding new products programmatically

2019-02-04 20:41发布

问题:

I am trying to add products to Magento 1.5 programmatically. My script will ultimately be a cron job, regularly updating and adding products as dictated by an XML file supplied by the accounts system.

I have a problem in creating new products. The relevant code segment from my script is:

    $attributeSetId = 4;

    //$newproduct = Mage::getModel('catalog/product');
    $newproduct = new Mage_Catalog_Model_Product();

    $newproduct->setTypeId('simple');
    $newproduct->setWeight($product->UnitWeight);       
    $newproduct->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH); 
    $newproduct->setStatus(1);
    $newproduct->setSKU($SKU);
    $newproduct->setTaxClassId(0);
    $newproduct->setWebsiteIDs(array(0)); 
    $newproduct->setStoreIDs(array(1)); 
    $newproduct->setStockData(array( 
        'is_in_stock' => 1, 
        'qty' => $XMLproduct->QtyInStock,
        'manage_stock' => 1
    )); 

    $newproduct->setAttributeSetId(4);
    $newproduct->setName($product->Name);
    $newproduct->setCategoryIds(array(3)); // array of categories it will relate to

    $newproduct->setDescription($product->LongDescription);
    $newproduct->setShortDescription($product->Description);
    $newproduct->setPrice($XMLproduct->SalePrice);

    try {
        if (is_array($errors = $newproduct->validate())) {
            $strErrors = array();
            foreach($errors as $code=>$error) {
                $strErrors[] = ($error === true)? Mage::helper('catalog')->__('Attribute "%s" is invalid.', $code) : $error;
            }
            $this->_fault('data_invalid', implode("\n", $strErrors));
        }

        $newproduct->save();
    } catch (Mage_Core_Exception $e) {
        $this->_fault('data_invalid', $e->getMessage());
    }

The product is 'half' created, but the script gives up throwing the following error:

PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`LittleDickyBird`.`catalog_category_product_index`, CONSTRAINT `FK_CATALOG_CATEGORY_PROD_IDX_CATEGORY_ENTITY` FOREIGN KEY (`category_id`) REFERENCES `catalog_category_entity` (`entity_id`) ON )' in /home/default/littledickybird.co.uk/user/htdocs/1.5/lib/Zend/Db/Statement/Pdo.php:228
Stack trace:
#0 /home/default/littledickybird.co.uk/user/htdocs/1.5/lib/Zend/Db/Statement/Pdo.php(228): PDOStatement->execute(Array)
#1 /home/default/littledickybird.co.uk/user/htdocs/1.5/lib/Zend/Db/Statement.php(300): Zend_Db_Statement_Pdo->_execute(Array)
#2 /home/default/littledickybird.co.uk/user/htdocs/1.5/lib/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array)
#3 /home/default/littledickybird.co.uk/user/htdocs/1.5/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('INSERT INTO `ca...', Array)
#4 /home/default/littledic in /home/default/littledickybird.co.uk/user/htdocs/1.5/lib/Zend/Db/Statement/Pdo.php on line 234

Can anyone, please, throw any light onto what I am missing or doing wrong. As you may be able to tell from my tone, I am pretty desperate, so any help will be very much appreciated.

Thank you

回答1:

AMP, the OP, already self-answered the question.

Quote:

Cool, I have found the problem, the line: $newproduct->setWebsiteIDs(array(0)); should be: $newproduct->setWebsiteIDs(array(1)); Amazing how the smallest thing can waste hours!

Note: It's absolutely OK to self-answer your own question. Please just post it as an real answer, but not in a question or comment. Posting as real answer helps to keep the "Unanswered" list more clear (avoids making other people wasting their time).



回答2:

Both @Jurgen and @Amp answers are perfect.

I think this could be done like this way so it becomes more dynamic

$newproduct->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));