You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopware 6:如何仅在分类不存在时执行创建分类代码

解决方案

要实现仅在“Profi-Shop”分类不存在时才执行创建逻辑,你需要先查询该分类是否存在,再根据查询结果决定是否执行创建操作,修改后的代码如下:

$categoryRepository = $this->container->get('category.repository');
$context = $context->getContext();

// 查询是否存在指定名称且父级为null的分类
$existingCategory = $categoryRepository->findOneBy([
    'name' => 'Profi-Shop',
    'parentId' => null
], $context);

// 仅当分类不存在时执行创建逻辑
if (!$existingCategory) {
    $newCategory = [
        'name' => 'Profi-Shop',
        'parentId' => null,
        'customFields' => [],
    ];

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

关键说明:

  • 用findOneBy方法传入名称和父级ID作为查询条件,确保匹配你要创建的分类的唯一特征
  • 若$existingCategory返回null,说明目标分类不存在,此时才执行创建操作
  • 保持查询和创建操作使用相同的上下文($context),避免环境不一致问题

内容的提问来源于stack exchange,提问作者Illia Yalovoi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 10:04:53