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
相关产品推荐
相关产品推荐

