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');


Any help will be appreciated


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
  • Okay, thanks a lot, I changed it by this $_product->setSku('test-SKU'.$item); But it appears this error: URL key for specified store already exists. – user60150 Nov 13 '17 at 11:17
  • @hanaayari This answer is right but not complete. You also need to set UrlKey. $_product->setUrlKey('test-SKU' . $item) – Bunyamin Inan Nov 13 '17 at 11:36
  • @hanaayari you should accept my answer if it helped you. – Vivek Kumar Nov 13 '17 at 11:43

Your Answer

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