英文:
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());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论