You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shopware命令类中获取商品URL?

在Shopware命令类中获取商品URL的方法

要在自定义命令类中获取商品的SEO友好URL,你需要借助Shopware内置的SEO路由服务,并确保查询商品时关联必要的字段,具体步骤如下:

1. 注入所需服务

在你的命令类构造函数中,注入ProductRepository(已存在)和ProductSeoUrlRoute服务,用于获取商品的SEO URL:

use Shopware\Core\Content\Seo\SeoUrlRoute\ProductSeoUrlRoute;
use Shopware\Core\Content\Product\ProductRepository;
use Symfony\Component\Console\Command\Command;

class YourCustomCommand extends Command
{
    private ProductRepository $productRepository;
    private ProductSeoUrlRoute $productSeoUrlRoute;

    public function __construct(ProductRepository $productRepository, ProductSeoUrlRoute $productSeoUrlRoute)
    {
        parent::__construct();
        $this->productRepository = $productRepository;
        $this->productSeoUrlRoute = $productSeoUrlRoute;
    }

    // 命令配置(configure方法)及执行逻辑(execute方法)
}

2. 关联商品的SEO URL字段

在查询商品时,必须通过Criteria添加seoUrls关联,否则无法获取商品的URL信息:

// 构建查询条件时添加关联
$cri->addAssociation('seoUrls');

$products = $this->productRepository->search($cri, $context)->getElements();

3. 获取并拼接商品URL

在循环处理商品时,筛选对应销售渠道的SEO URL,若需要完整域名还需拼接销售渠道的域名:

/** @var \Shopware\Core\Content\Product\ProductEntity $product */
foreach ($products as $product) {
    // 采用当前上下文的销售渠道ID,若需指定特定渠道可手动传入对应ID
    $salesChannelId = $context->getSource()->getSalesChannelId();
    
    // 筛选对应销售渠道的SEO URL
    $seoUrl = $product->getSeoUrls()->filter(function ($seoUrl) use ($salesChannelId) {
        return $seoUrl->getSalesChannelId() === $salesChannelId;
    })->first();

    $productUrl = null;
    if ($seoUrl) {
        // 获取SEO路径(示例:/product/your-product-slug)
        $seoPath = $seoUrl->getSeoPathInfo();
        
        // 若需要完整带域名的URL,需先查询对应销售渠道的域名
        // 可注入SalesChannelRepository实现:
        // $salesChannel = $this->salesChannelRepository->search(new Criteria([$salesChannelId]), $context)->first();
        // $domain = $salesChannel->getDomains()->first()->getUrl();
        // $productUrl = rtrim($domain, '/') . $seoPath;
        
        // 仅需相对路径的话直接使用seoPath即可
        $productUrl = $seoPath;
    }

    $formattedProduct = [
        'id' => $product->get('id'),
        'title' => $product->get('translated')['name'],
        'description' => $product->get('translated')['description'],
        'link' => $productUrl ?? 'URL未生成'
    ];

    $formattedProducts[] = $formattedProduct;
}

额外注意事项

  • 若商品尚未生成SEO URL,可注入SeoUrlUpdater服务,调用update方法手动生成:
    $this->seoUrlUpdater->update([$product->getId()], $context);
    
  • 多销售渠道场景下,需明确指定目标销售渠道ID,不同渠道的商品URL可能不同
  • 若需要严格遵循销售渠道路由规则,可使用ProductUrlGenerator服务,但需先构建SalesChannelContext再调用生成方法

内容的提问来源于stack exchange,提问作者Leon Schwanitz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 23:52:44