使用计划任务按categoryId检查产品

问题描述 投票:0回答:1

我想使用计划任务来检查特定类别是否有产品。我曾经使用

product.repository
通过
categoryId
获取产品,但是这个方法不起作用。例如,如果“衣服”类别在店面中显示 2 个产品,则使用
product.repository
时我会得到 null。

我想使用product_listing,但我无法在计划任务中使用SalesChannelContext。您有想法吗,如何获得特定类别在店面中显示的总产品?

#[AsMessageHandler(handles: CategoriesTask::class)]
class CategoriesTaskHandler extends ScheduledTaskHandler
{
    private EntityRepository $productRepository;

    private EntityRepository $categoryRepository;

    public function __construct(
        EntityRepository $productRepository,
        EntityRepository $categoryRepository,
    {
        $this->productRepository = $productRepository;
        $this->categoryRepository = $categoryRepository;
    }

    public function run(): void
    {
        $data = [];
        $productsTotal = 0;

        $context = Context::createDefaultContext();

        $categories = $this->categoryRepository->search(new Criteria(), $context);
        foreach ($categories as $category) {
            $criteria = new Criteria();
            $criteria->addAssociation('categories');
            $criteria->addFilter(new EqualsFilter('categories.id', $category->getId()));

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

            $data[] = [
                'categoryName' => $category->getName(),
                'products' => $products->getTotal(),
            ];
        }

        dump($data);
    }
}
scheduled-tasks shopware shopware6
1个回答
0
投票

如果您访问普通存储库,则不需要 salesChannel 上下文,例如:

$defaultContext = Context::createDefaultContext();
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('product.categories.id', $categoryId)); // or something similar
$this->productRepository->search($criteria, $defaultContext);

但是如果需要访问销售渠道存储库,您可以创建销售渠道上下文。您需要相应的 salesChannel Id,第三个参数(带有语言 ID)是选项,但有助于在必要时获取正确的数据,然后重新加载 cartRuleLoader 以应用所有必要的规则(如动态访问等)。然后就可以加载销售渠道依赖的产品了。

$token = Uuid::fromStringToHex($id);
$salesChannelContext = $this->salesChannelContextFactory->create(
            $token,
            $salesChannelId,
            [
                SalesChannelContextService::LANGUAGE_ID => $languageId
            ]
        );
$this->cartRuleLoader->loadByToken($salesChannelContext, $token);
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('product.categories.id', $categoryId)); // or something similar
$salesChannelProduct = $this->salesChannelProductRepository->search(
                    $criteria, $salesChannelContext
                );
© www.soinside.com 2019 - 2024. All rights reserved.