In this blog, you are going to learn “How to get data according to sales channel using the sales channel repository .”
I hope you know the directory structure of Shopware 6 plugin, if you don’t know, see here- https://docs.shopware.com/en/shopware-platform-dev-en/internals/directory-structure.
The Purpose of using sales channel in the repository is getting data according to sales channel and it save the request time and much fast because it basically add the filter of sales channel in the repository.
services.xml
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="WebkulTest\Service\UserService">
<argument type="service" id="sales_channel.product.repository"/>
</service>
</services>
</container>
Create an services.xml
file, follow the directory structure:- <plugin root>/src/Resources/config/services.xml
Add the service, in type
attribute put service and in id
add sales_channel followed by entity name.
This added the product
entity as sales channel in the service.
UserService.php
<?php declare(strict_types=1);
namespace WebkulTest\Service;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\System\SalesChannel\Entity\SalesChannelRepositoryInterface;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
class UserService
{
/**
* @var SalesChannelRepositoryInterface
*/
private $productRepository;
public function __construct(SalesChannelRepositoryInterface $productRepository)
{
$this->productRepository = $productRepository;
}
public function load(SalesChannelContext $context)
{
$criteria = new Criteria();
$criteria->addAssociation('cover');
$criteria->addAssociation('options.group');
$products = $this->productRepository->search($criteria, $context);
return $products;
}
}
Create an service file or add them in any where according to your need.Normally we use EntityRepositoryInterface
to fetch, write the data but in the case we are using the SalesChannelRepositoryInterface
. SalesChannelRepositoryInterface have only three function like search, aggregate, searchIds.
It take two parameters, first one is criteria and second is SaleschannelContext whereas EntityRepositoryInterface have more function and it take two parameters, first is criteria and second is Context. Only Difference is in two parameter.
SalesChannelRepositoryInterface require the sales channel definition and entity, so also create them by using SalesChannelDefinitionInterface.
You can view in the core part, by followed the path of product :- <shopware/platform/src/core/content/product/salesChannel/SalesChannelProductDefinition
.
Hope it will help you. Thanks for reading. Happy Coding
Thank You.