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

Shopware 6:命令/调度器中按商品流获取带指定货币与店铺语言的商品

在Shopware命令/调度器中获取指定商品流的商品并应用货币与语言

由于命令或调度器执行环境没有自动生成的请求上下文,需要手动构建上下文并结合相关服务实现需求,具体步骤如下:

1. 注入/获取所需服务

在命令类中通过构造函数注入核心服务(推荐方式):

public function __construct(
    private readonly SalesChannelRepository $salesChannelRepository,
    private readonly ProductStreamRepository $productStreamRepository,
    private readonly ProductStreamService $productStreamService,
    private readonly ProductRepository $productRepository,
    private readonly CurrencyRepository $currencyRepository,
    private readonly LanguageRepository $languageRepository
) {
    parent::__construct();
}

2. 加载基础实体

从给定ID获取对应实体,确保数据有效性:

// 加载目标销售渠道
$salesChannel = $this->salesChannelRepository->search(new Criteria([$salesChannelId]), Context::createDefault())->first();
if (!$salesChannel) {
    throw new \RuntimeException("销售渠道不存在,ID: {$salesChannelId}");
}

// 加载销售渠道默认语言
$defaultLanguageId = $salesChannel->getLanguageId();
$language = $this->languageRepository->search(new Criteria([$defaultLanguageId]), Context::createDefault())->first();
if (!$language) {
    throw new \RuntimeException("语言不存在,ID: {$defaultLanguageId}");
}

// 加载指定货币
$currency = $this->currencyRepository->search(new Criteria([$currencyId]), Context::createDefault())->first();
if (!$currency) {
    throw new \RuntimeException("货币不存在,ID: {$currencyId}");
}

3. 手动构建上下文

创建包含语言、货币、销售渠道信息的上下文,确保商品数据匹配指定环境:

// 使用系统匿名用户ID构建上下文(如需权限可替换为管理员用户ID)
$context = new Context(
    SystemUser::createAnonymousId(),
    [$defaultLanguageId],
    $salesChannelId,
    true,
    [new CurrencyStruct($currency->getId(), $currency->getIsoCode())],
    $language->getId()
);

4. 获取商品流中的商品

加载目标商品流,执行筛选逻辑并获取完整商品数据:

// 加载目标商品流
$productStream = $this->productStreamRepository->search(new Criteria([$productStreamId]), Context::createDefault())->first();
if (!$productStream) {
    throw new \RuntimeException("商品流不存在,ID: {$productStreamId}");
}

// 获取商品流筛选后的商品ID列表
$productIds = $this->productStreamService->getIds($productStream, $context);

// 加载完整商品数据(可按需添加关联字段,如价格、分类)
$productCriteria = new Criteria($productIds);
$productCriteria->addAssociation('prices');
$products = $this->productRepository->search($productCriteria, $context)->getEntities();

关键说明

  • 手动构建的上下文会自动让商品流筛选、商品数据返回时应用指定的语言(本地化字段)和货币(商品价格)规则
  • ProductStreamService::getIds() 会执行商品流的内置筛选逻辑,返回符合条件的商品ID集合

内容的提问来源于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.14 19:42:08