检查类别是否存在 Shopware 6

huangapple go评论74阅读模式
英文:

Check if a category exists Shopware 6

问题

检查分类是否存在your text

我有这样的代码

 $categoryService = $this->container->get('category.repository');
    $newCategory = [
            'name' => 'Profi-Shop',
            'parentId' => null,
            'customFields' => [
        ],
    ];

    $categoryService->create([$newCategory], $context->getContext());

它每次都被执行。如何仅在没有这样的分类时执行它。

英文:

Check if a category existsyour text

I have such code

 $categoryService = $this->container->get('category.repository');
    $newCategory = [
            'name' => 'Profi-Shop',
            'parentId' => null,
            'customFields' => [
        ],
    ];

    $categoryService->create([$newCategory], $context->getContext());

It is executed every time. How to execute it only if there is no such category

答案1

得分: 1

你需要在创建类别之前检查它是否已存在。如果存在,则跳过创建步骤:

use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;

$categoryService = $this->container->get('category.repository');
$newCategoryName = 'Profi-Shop';

// 首先搜索类别
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('name', $newCategoryName));
$existingCategory = $categoryService->search($criteria, $context->getContext());

// 如果没有找到匹配项,则创建它:
if ($existingCategory->getTotal() === 0) {
    $newCategory = [
        'name' => $newCategoryName,
        'parentId' => null,
        'customFields' => [],
    ];

    $categoryService->create([$newCategory], $context->getContext());
}
英文:

You need to check if your category exists prior creating it. If it does, then just skip creation step:

use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;

$categoryService = $this->container->get('category.repository');
$newCategoryName = 'Profi-Shop';

// Search for the category first
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('name', $newCategoryName));
$existingCategory = $categoryService->search($criteria, $context->getContext());

// Create it if there's no match found:
if ($existingCategory->getTotal() === 0) {
    $newCategory = [
        'name' => $newCategoryName,
        'parentId' => null,
        'customFields' => [],
    ];

    $categoryService->create([$newCategory], $context->getContext());
}

huangapple
  • 本文由 发表于 2023年4月13日 21:25:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76005986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定