0

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

1

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
3
  • 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