skip to Main Content

I tried importing a single product in magento 2..It failed..

I tried a script in magento 2 root directory and
My code is

 <?php 
use MagentoFrameworkAppBootstrap;
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$params[Bootstrap::PARAM_REQUIRE_MAINTENANCE] = true; // default false
$params[Bootstrap::PARAM_REQUIRE_IS_INSTALLED] = false; // default true
$bootstrap = Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('MagentoFrameworkAppState');
$state->setAreaCode('frontend');

    $simple_product = $objectManager->create('MagentoCatalogModelProduct');
    $simple_product->setSku('Tops');
    $simple_product->setName('tops');
    $simple_product->setAttributeSetCode('Default');
    $simple_product->setCategories('Default Category/Women');
    $simple_product->setStatus(1);
    $simple_product->setTypeId('simple');
    $simple_product->setPrice(10);
    $simple_product->setProductWebsites('base');
    $simple_product->setCategoryIds(array(31));
    $simple_product->setUrlKey ('tops');
$simple_product->setColor('Red');
    $simple_product->setStockData(array(
        'use_config_manage_stock' => 0, //'Use config settings' checkbox
        'manage_stock' => 1, //manage stock
        'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
        'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
        'is_in_stock' => 1, //Stock Availability
        'qty' => 100 //qty
        )
    );

    $simple_product->save();

    $simple_product_id = $simple_product->getId();
    echo "simple product id: ".$simple_product_id."n";
?>

and i am getting the following error

Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento`.`catalog_product_entity`, CONSTRAINT `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 DELET) in /var/www/html/magento/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php:228 Stack trace: #0 /var/www/html/magento/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php(228): PDOStatement->execute(Array) #1 /var/www/html/magento/vendor/magento/framework/DB/Statement/Pdo/Mysql.php(95): Zend_Db_Statement_Pdo->_execute(Array) #2 /var/www/html/magento/vendor/magento/zendframework1/library/Zend/Db/Statement.php(303): MagentoFrameworkDBStatementPdoMysql->_execute(Array) #3 /var/www/html/magento/vendor/magento/zendframework1/library/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array) #4 /var/www/html/magento/vendor/magento/zendframework1/ in /var/www/html/magento/vendor/magento/zendframework1/library/Zend/Db/Statement/Pdo.php on line 235

Can anyone give me a solution?

4

Answers


  1. This is the updated version of your code. Please use this code to create product.

    use MagentoFrameworkAppBootstrap;
    include("app/bootstrap.php");
    $bootstrap = Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $objectManager = $bootstrap->getObjectManager();
    $state = $objectManager->get('MagentoFrameworkAppState');
    $state->setAreaCode('frontend');
    $simple_product = $objectManager->create('MagentoCatalogModelProduct');
    $simple_product->setSku('tops123');
    $simple_product->setName('tops');
    $simple_product->setAttributeSetId(4);;
    $simple_product->setCategories('Default Category/Women');
    $simple_product->setStatus(1);
    $simple_product->setTypeId('simple');
    $simple_product->setPrice(10);
    $simple_product->setWebsiteIds(array(1));
    $simple_product->setCategoryIds(array(31));
    $simple_product->setUrlKey ('tops343225');
    $simple_product->setColor('Red');
    $simple_product->setStockData(array(
        'use_config_manage_stock' => 0, //'Use config settings' checkbox
        'manage_stock' => 1, //manage stock
        'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
        'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
        'is_in_stock' => 1, //Stock Availability
        'qty' => 100 //qty
        )
    );
    
    
    $simple_product->save();
    $simple_product_id = $simple_product->getId();
    echo "simple product id: ".$simple_product_id."n";
    

    Thanks

    Login or Signup to reply.
  2. For Simple Product Working on M2

    use MagentoFrameworkAppBootstrap;
    
    include("../app/bootstrap.php");
    $bootstrap = Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $state = $objectManager->get('MagentoFrameworkAppState');
    $state->setAreaCode('frontend');
    
    $simpleProduct = $objectManager->create('MagentoCatalogModelProduct');
    $simpleProduct->setSku('Testing3');
    $simpleProduct->setName('Testing3');
    $simpleProduct->setAttributeSetId(9);
    $simpleProduct->setCategoryIds(3);
    $simpleProduct->setDescription('This is for testing');
    $simpleProduct->setStatus(1);
    $simpleProduct->setTypeId('simple');
    $simpleProduct->setPrice(500);
    $simpleProduct->setWebsiteIds(array(1));
    $simpleProduct->setVisibility(4);
    $simpleProduct->setUrlKey('Testing3');
    
    $simpleProduct->setStockData(array(
        'is_in_stock' => 1, //Stock Availability
        'qty' => 100//qty
            )
    );
    
    $attr = $simpleProduct->getResource()->getAttribute('color');
    $attributeOptionId = $attr->getSource()->getOptionId('Red'); //name in Default Store View
    $simpleProduct->setData('color', $attributeOptionId);
    
    $simpleProduct->save();
    $simpleProductId = $simpleProduct->getId();
    echo "Simple Product ID: " . $simpleProductId . "n";
    ?>
    

    Login or Signup to reply.
  3. For configurable product working on M2

    <?php
    
    use MagentoFrameworkAppBootstrap;
    
    include("../app/bootstrap.php");
    $bootstrap = Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $state = $objectManager->get('MagentoFrameworkAppState');
    $state->setAreaCode('frontend');
    
    
    $productId = 809; // Configurable Product Id
    $objectManager = MagentoFrameworkAppObjectManager::getInstance();
    $product = $objectManager->create('MagentoCatalogModelProduct')->load($productId); // Load Configurable Product
    $attributeModel = $objectManager->create('MagentoConfigurableProductModelProductTypeConfigurableAttribute');
    $position = 0;
    $attributes = array(93, 135); // Super Attribute Ids Used To Create Configurable Product
    $associatedProductIds = array(806, 807); //Product Ids Of Associated Products
    foreach ($attributes as $attributeId) {
        $data = array('attribute_id' => $attributeId, 'product_id' => $productId, 'position' => $position);
        $position++;
        $attributeModel->setData($data)->save();
    }
    $product->setTypeId("configurable"); // Setting Product Type As Configurable
    $product->setAffectConfigurableProductAttributes(4);
    $objectManager->create('MagentoConfigurableProductModelProductTypeConfigurable')->setUsedProductAttributeIds($attributes, $product);
    $product->setNewVariationsAttributeSetId(9); // Setting Attribute Set Id
    $product->setAssociatedProductIds($associatedProductIds); // Setting Associated Products
    $product->setCanSaveConfigurableAttributes(true);
    $product->save();
    $configProductId = $product->getId();
            echo "Configurable product id: " . $configProductId . "n";
    ?>
    
    Login or Signup to reply.
  4.  <?php 
    use MagentoFrameworkAppBootstrap;
    
    include("./app/bootstrap.php");
    $bootstrap = Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $state = $objectManager->get('MagentoFrameworkAppState');
    $state->setAreaCode('frontend');
     // add logging capability
    $writer = new ZendLogWriterStream(BP . '/var/log/import-new.log');
    $logger = new ZendLogLogger();
    $logger->addWriter($writer);
                $simpleProduct = $objectManager->create('MagentoCatalogModelProduct');
                $simpleProduct->setSku('Testing5');
                $simpleProduct->setName('Testing11115');
                // $attributeSetId = $simpleProduct->getDefaultAttributeSetId();
                $simpleProduct->setAttributeSetId(4);
                $simpleProduct->setCategoryIds(3);
                $simpleProduct->setDescription('This is for testing');
                $simpleProduct->setStatus(1);
                $simpleProduct->setTypeId('simple');
                $simpleProduct->setPrice(500);
                $simpleProduct->setWebsiteIds(array(1));
                $simpleProduct->setVisibility(4);
                $simpleProduct->setUrlKey('Testing445');
                $simpleProduct->setStoreId(1);
                $simpleProduct->setStockData(array(
                    'is_in_stock' => 1, //Stock Availability
                    'qty' => 100//qty
                        )
                );
    
                // $attr = $simpleProduct->getResource()->getAttribute('color');
                // $attributeOptionId = $attr->getSource()->getOptionId('Red'); //name in Default Store View
                // $simpleProduct->setData('color', $attributeOptionId);
    
                $simpleProduct->save();
                $simpleProductId = $simpleProduct->getId();
                echo "Simple Product ID: " . $simpleProductId . "n";
    
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search