Azngeek
Azngeek

Reputation: 2503

Shopware 6 - Get products associated to a a specific sales channel from a product repository

Situation

I am building a CLI-command to get all products, which are associated to a given sales-channel. For example i would like to have all products from the B2B-channel.

Current approach

From reading the documentation my understanding is that i need to do the following:

  1. Create a sales-channel context using the Shopware\Core\System\SalesChannel\Context\SalesChannelContextFactory
  2. Pass context to a product repository

Here is some pseudo-code. I use the RepositoryIterator but basically it just wraps any EntityRepositoryInterface. In this case a product repository.

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

What i get now if i loop through the repository is still a list of all entities instead of the one specific to the provided sales channel.

So what i am missing?

Upvotes: 1

Views: 2216

Answers (1)

Azngeek
Azngeek

Reputation: 2503

I figured it out now. It seems like that the SalesChannelContext is not enough. You also need to add a filter. This is the expected behaviour in the admin-area.

So this would be the criteria:

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

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

It still does not feel intuitive as the responsibility of the SalesChannelContext is not clear for me.

Upvotes: 1

Related Questions