检查类别是否存在 Shopware 6

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

Check if a category exists Shopware 6

问题

检查分类是否存在your text

我有这样的代码

  1. $categoryService = $this->container->get('category.repository');
  2. $newCategory = [
  3. 'name' => 'Profi-Shop',
  4. 'parentId' => null,
  5. 'customFields' => [
  6. ],
  7. ];
  8. $categoryService->create([$newCategory], $context->getContext());

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

英文:

Check if a category existsyour text

I have such code

  1. $categoryService = $this->container->get('category.repository');
  2. $newCategory = [
  3. 'name' => 'Profi-Shop',
  4. 'parentId' => null,
  5. 'customFields' => [
  6. ],
  7. ];
  8. $categoryService->create([$newCategory], $context->getContext());

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

答案1

得分: 1

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

  1. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  2. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  3. $categoryService = $this->container->get('category.repository');
  4. $newCategoryName = 'Profi-Shop';
  5. // 首先搜索类别
  6. $criteria = new Criteria();
  7. $criteria->addFilter(new EqualsFilter('name', $newCategoryName));
  8. $existingCategory = $categoryService->search($criteria, $context->getContext());
  9. // 如果没有找到匹配项,则创建它:
  10. if ($existingCategory->getTotal() === 0) {
  11. $newCategory = [
  12. 'name' => $newCategoryName,
  13. 'parentId' => null,
  14. 'customFields' => [],
  15. ];
  16. $categoryService->create([$newCategory], $context->getContext());
  17. }
英文:

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

  1. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  2. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  3. $categoryService = $this->container->get('category.repository');
  4. $newCategoryName = 'Profi-Shop';
  5. // Search for the category first
  6. $criteria = new Criteria();
  7. $criteria->addFilter(new EqualsFilter('name', $newCategoryName));
  8. $existingCategory = $categoryService->search($criteria, $context->getContext());
  9. // Create it if there's no match found:
  10. if ($existingCategory->getTotal() === 0) {
  11. $newCategory = [
  12. 'name' => $newCategoryName,
  13. 'parentId' => null,
  14. 'customFields' => [],
  15. ];
  16. $categoryService->create([$newCategory], $context->getContext());
  17. }

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:

确定