首页 > 解决方案 > Magento 2 URL重写问题:指定商店的URL密钥已经存在

问题描述

我在 Magento 2.2.5 上以编程方式保存产品时遇到了这个问题

在任何模块中,如果我在多个产品的循环内执行$product->save();OR 。$this->productRepository->save($product);我得到:

PDOException:SQLSTATE [23000]:完整性约束违规:1062 /home/dev3/www/vendor/magento/zendframework1/library/Zend/Db/Statement/ 中键“URL_REWRITE_REQUEST_PATH_STORE_ID”的重复条目“the-lipstick.html-1” pdo.php:228

该错误类似于此处描述的错误:https ://www.human-element.com/url-key-specified-store-already-exists-magento-2/

使用管理区域登录可以很好地保存产品。

到目前为止,任何建议的修复程序,包括修改核心文件 (DBStorage.php) 的修复程序都不适用于 2.2.5。

到目前为止我尝试了什么: 1. 从https://www.human-element.com/url-key-specified-store-already-exists-magento-2/ 修复 2. 从https://magento.stackexchange 修复。 com/questions/210359/magento-2-product-url-rewrite-issue

请为 M 2.2.5 提出解决方案/修复

标签: phpmagentomagento2

解决方案


我的修复:在 di.xml -

<preference for="Magento\UrlRewrite\Model\Storage\DbStorage" type="MyCompany\FixUrls\Model\ProductUrlFix" />

在 ProductFixUrl 中编写这两个函数:

protected function doReplace(array $urls){

    $this->deleteOld($urls);
        $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();
        }
        try {

            $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]);
                    }
                }
            }
            parent::insertMultiple($data);

        } catch (\Magento\Framework\Exception\AlreadyExistsException $e) {
            /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewrite[] $urlConflicted */
            $urlConflicted = [];
            foreach ($urls as $url) {
                $urlFound = parent::doFindOneByData(
                    [
                        UrlRewriteData::REQUEST_PATH => $url->getRequestPath(),
                        UrlRewriteData::STORE_ID => $url->getStoreId(),
                    ]
                );
                if (isset($urlFound[UrlRewriteData::URL_REWRITE_ID])) {
                    $urlConflicted[$urlFound[UrlRewriteData::URL_REWRITE_ID]] = $url->toArray();
                }
            }
            if ($urlConflicted) {
                throw new \Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException(
                    __('URL key for specified store already exists.'),
                    $e,
                    $e->getCode(),
                    $urlConflicted
                );
            } else {
                throw $e->getPrevious() ?: $e;
            }
        }

        return $urls;
    }

    /**
     * @param UrlRewrite[] $urls
     *
     * @return void
     */
    public function deleteOld(array $urls)
    {
        $oldUrlsSelect = $this->connection->select();
        $oldUrlsSelect->from(
            $this->resource->getTableName(self::TABLE_NAME)
        );
        /** @var UrlRewrite $url */
        foreach ($urls as $url) {
            $oldUrlsSelect->orWhere(
                $this->connection->quoteIdentifier(
                    UrlRewrite::ENTITY_TYPE
                ) . ' = ?',
                $url->getEntityType()
            );
            $oldUrlsSelect->where(
                $this->connection->quoteIdentifier(
                    UrlRewrite::ENTITY_ID
                ) . ' = ?',
                $url->getEntityId()
            );
            $oldUrlsSelect->where(
                $this->connection->quoteIdentifier(
                    UrlRewrite::STORE_ID
                ) . ' = ?',
                $url->getStoreId()
            );
        }

        // prevent query locking in a case when nothing to delete
        $checkOldUrlsSelect = clone $oldUrlsSelect;
        $checkOldUrlsSelect->reset(Select::COLUMNS);
        $checkOldUrlsSelect->columns('count(*)');
        $hasOldUrls = (bool) $this->connection->fetchOne($checkOldUrlsSelect);

        if ($hasOldUrls) {
            $this->connection->query(
                $oldUrlsSelect->deleteFromSelect(
                    $this->resource->getTableName(self::TABLE_NAME)
                )
            );
        }
    }

推荐阅读