Skip to content

IMPORT PRODUCT : url key for specified store already exists

I have this method which is meant to save the product during an import script.

protected function saveProduct($product, $urlKeySuffix = 0, $baseUrlKey = false)
{
    $savedProd = null;
    try {
        if($urlKeySuffix) $product->setUrlKey($baseUrlKey . '_' . $urlKeySuffix);
        $savedProd = $this->productRepository->save($product);
    } catch (AlreadyExistsException $e) {
        $urlKeySuffix++;
        $baseUrlKey = $baseUrlKey ?: $product->getUrlKey();
        try{
            $savedProd = $this->saveProduct($product, $urlKeySuffix, $baseUrlKey);
        }catch (Exception $e){
            $customLog->logError($e->getMessage());
        }
    }
    return $savedProd;
}

On my database i indeed have the original url key that is trying to be inserted. Which is why this code increase the digit on the url key.

If i log the new url key before each save i can see it’s well increasing…but sadly i keep taking the url key duplicate error and i can’t understand why as i don’t have nothign more.

Ex If I have url key = generic in my database then at the second iteration generic-1 should work as it’s not on my database product_catalog_entity_varchar.

Am I missing something there ?