In this topic, We will discuss the important issue which is generally you can see while you saving category in the backend, saving the product in the backend side or while running the command for re-indexing product.
This error generally occurs when you have more than one store, When you have a product and Category with the same URL key.
For fix this issues, He I am suggesting two solutions are as below:
1st solution:
Just go to your database and clean up the “url_rewrite” table.
Also, change the “url_key” of all categories. You can also write the “UpgradeData” script for this solution.
2nd solution:
Remove the duplication data when saving the category.
This data you will get on this method doReplace($urls) and in the following path: \vendor\magento\module-url-rewrite\Model\Storage\DbStorage.php file.
protected function doReplace($urls)
{
foreach ($this->createFilterDataBasedOnUrls($urls) as $type => $urlData) {
$urlData[UrlRewrite::ENTITY_TYPE] = $type;
$this->deleteByData($urlData);
}
$data = [];
foreach ($urls as $url) {
$data[] = $url->toArray();
}
$this->insertMultiple($data);
}
After finding a lot, we found the $data variable has duplicate records.
If you want the above method will work without any errors.
Rewrite this method with the below code:
protected function doReplace($urls)
{
foreach ($this->createFilterDataBasedOnUrls($urls) as $type => $urlData) {
$urlData[UrlRewrite::ENTITY_TYPE] = $type;
$this->deleteByData($urlData);
}
$data = [];
$storeId_requestPaths = [];
foreach ($urls as $url) {
$storeId = $url->getStoreId();
$requestPath = $url->getRequestPath();
// Skip if is exist in the database
$sql = "SELECT * FROM url_rewrite where store_id = $storeId and request_path = '$requestPath'";
$exists = $this->connection->fetchOne($sql);
if ($exists) continue;
$storeId_requestPaths[] = $storeId . '-' . $requestPath;
$data[] = $url->toArray();
}
// Remove duplication data;
$n = count($storeId_requestPaths);
for ($i = 0; $i < $n - 1; $i++) {
for ($j = $i + 1; $j < $n; $j++) {
if ($storeId_requestPaths[$i] == $storeId_requestPaths[$j]) {
unset($data[$j]);
}
}
}
$this->insertMultiple($data);
}
Above solutions are too effective and accurate to perform. I performed complete and tested successfully.
If you tried this and found any issues or error, then you can email me to get help more. Me Magento Developer Rajan Soni will surely helps you.
Hello There,
Thanks for your information I just fixed the issue as per your given steps in the blog.
Thank you again!
This extension solves this problem for you https://webpanda-solutions.com/url-rewrites-regenerate-and-customize.html