一个相当简单的解决方案是使用准备好运行的Magento 2模块,它完全可以完成重写索引器的工作。您可以通过代码或从命令行调用此重新生成。更好的解决方案是通过您自己的导入器模块中的代码来完成。再生很简单
foreach($list as $product) {
if($store_id === Store::DEFAULT_STORE_ID)
$product->setStoreId($store_id);
$this->urlPersist->deleteByData([
UrlRewrite::ENTITY_ID => $product->getId(),
UrlRewrite::ENTITY_TYPE => ProductUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::REDIRECT_TYPE => 0,
UrlRewrite::STORE_ID => $store_id
]);
try {
$this->urlPersist->replace(
$this->productUrlRewriteGenerator->generate($product)
);
} catch(\Exception $e) {
$out->writeln('<error>Duplicated url for '. $product->getId() .'</error>');
} }
正如你所看到的Magento 2为您提供了再生的URL重写模式\ Magento的\ CatalogUrlRewrite \型号\ ProductUrlRewriteGenerator(productUrlRewriteGenerator),你可以注入到你的模型。这个生成的url重写可以被替换为\ Magento \ UrlRewrite \ Model \ UrlPersistInterface(urlPersist)。您可以在导入后为所有产品或在更改后为每个单一产品循环运行。
或者您可以检出https://github.com/Iazel/magento2-regenurl