skip to Main Content

I am uploading product programmatically in Magento2 I have same name product with different SKU but when I run script Magento 2 gives an error because of Url Key :

Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'reine-de-naples-jour-nuit-8998.html-1' for key 'URL_REWRITE_REQUEST_PATH_STORE_ID

my script is those we use to save a product programmatically

<?php
use MagentoFrameworkAppBootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$objectManager1 = MagentoFrameworkAppObjectManager::getInstance();
$directoryList = $objectManager1->get('MagentoFrameworkAppFilesystemDirectoryList');
$path = $directoryList->getPath('media');
//var_dump($path); die;



$state = $objectManager->get('MagentoFrameworkAppState');
$state->setAreaCode('frontend');
$myarray = glob("Book2.csv"); 
usort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));
if(count($myarray)){
    /*This will create an array of associative arrays with the first row column headers as the keys.*/
    $csv_map = array_map('str_getcsv', file($myarray[count($myarray)-1]));
    array_walk($csv_map, function(&$a) use ($csv_map) {
      $a = array_combine($csv_map[0], $a);
    });
    array_shift($csv_map); # remove column header
    /*End*/

    $message = '';
    $count   = 1;
    foreach($csv_map as $data){ 
        //echo '<pre>';print_r($data);exit;

$product = $objectManager->create('MagentoCatalogModelProduct');
$product->setName(trim($data['Name']));
$product->setTypeId('simple');
$product->setAttributeSetId(4);
$product->setSku(trim($data['model_no']));
$product->setURL(trim($data['Name']).trim($data['model_no']));
$product->setWebsiteIds(array(1));
$product->setVisibility(4);
$product->setCreatedAt(strtotime('now'));
$product->setPrice(trim($data['price']));
//$_product->setShortDescription(trim($data['Short Description'])); // add text attribute
//$_product->setDescription(trim($data['Long Description'])); // add text attribute
 $img_url = trim($data['img_big']);

                //$lastWord = substr($img_url, strrpos($img_url, '/') + 1);

                //copy($img_url, 'pub/media/product/');
                $dir = $directoryList->getPath('media').'/big/';
                $imgpath = $dir.$img_url;
                //echo $imgpath; die;
                /*$_product->addImageToMediaGallery($imgpath, array('image','thumbnail','small_image'), false, false); */
                $product->addImageToMediaGallery($imgpath, array('image', 'small_image', 'thumbnail'), false, false);
//$_product->setImage($imgpath);
//$_product->setSmallImage($imgpath);
//$_product->setThumbnail($imgpath);
$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
        )
    );

$product->save();

    }
echo'success';
    }
?>

please suggest how to add Url key to script my script is working fine without the same name

2

Answers


  1. Have you tried omitting that field, so Magento generates the url_key itself?

    If you want model_no to be in the url (due to SEO requirements, I suppose) you’d better add it to name, which could be even better for SEO

    $product->setName(trim($data['Name']) . trim($data['model_no']));
    

    Feel free to join https://magento.stackexchange.com/questions & post more details about what you want

    Login or Signup to reply.
  2. You are using set on wrong attribute i.e setUrl() instead you should use setUrlKey() and because you are not setting different url keys so magento is trying to use name for generating url keys and as you have same names for multiple products so it ends up trying to save same keys for multiple products which is giving you this error.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search