Add Product Programmatically in Magento 2 – Fix Unique Constraint Violation

create-productmagento2product

I added this script to add several products, but it appears this error:

Unique constraint violation found

enter image description here

 $countallproduct = count($allproduct);
        for ($item = 1; $item < $countallproduct; $item++) {
            $product_data = $allproduct[$item];
            $objectManager =    \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
            $_product = $objectManager->create('\Magento\Catalog\Model\Product');
            $_product->setName($product_data->_source->name);
            $_product->setTypeId('simple');
            $_product->setAttributeSetId(4);
            $_product->setSku('test-SKU');
            $_product->setWebsiteIds(array(1));
            $_product->setVisibility(4);
            $_product->setPrice($product_data->_source->price);
            $_product->save();
        }

    }

Any help will be appreciated

Best Answer

You are setting same sku for all products in loop, the sku needs to be unique for every product. Change test-SKU in following code to something dynamic such as index of the loop or something

 $_product->setSku('test-SKU'); //needs to be unique for each product
Related Topic