您需要在创建类别之前判断您的类别是否存在.如果是这样,那么只需跳过创建步骤:
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());
}