首页 > 解决方案 > Shopware 6 - 从产品存储库中获取与特定销售渠道相关联的产品

问题描述

情况

我正在构建一个 CLI 命令来获取与给定销售渠道相关联的所有产品。例如,我想拥有 B2B 渠道的所有产品。

目前的方法

通过阅读文档,我的理解是我需要执行以下操作:

  1. 使用Shopware\Core\System\SalesChannel\Context\SalesChannelContextFactory
  2. 传递context到产品存储库

这是一些伪代码。我使用,RepositoryIterator但基本上它只是包装任何EntityRepositoryInterface. 在这种情况下,产品存储库。

$options = [
    SalesChannelContextService::LANGUAGE_ID => MY_STORE::B2B
];
$salesChannelContext = $this->salesChannelContextFactory->create('', $this->salesChannelId, $options);
return new RepositoryIterator($productRepository, $this->salesChannelContext->getContext(), $criteria);

如果我遍历存储库,我现在得到的仍然是所有实体的列表,而不是特定于所提供销售渠道的实体。

那么我错过了什么?

标签: shopware

解决方案


我现在想通了。似乎这SalesChannelContext还不够。您还需要添加过滤器。这是管理区域中的预期行为。

所以这将是标准:

...
$criteria = new Criteria();
$criteria->addFilter(new EqualsAnyFilter('visibilities.salesChannel.id', [$this->salesChannelId]));
...

return new RepositoryIterator($this->productRepository, $this->salesChannelContext->getContext(), $criteria);

它仍然感觉不直观,因为SalesChannelContext我的责任并不清楚。


推荐阅读