I'm trying to retrieve in some custom code the existing attribute groups from multiple attribute sets.
For this, I am using the Magento\Eav\Model\Attribute\GroupRepository::getList
method with search criteria builders and filters.
But I get a Magento\Framework\Exception\NoSuchEntityException
with the message No such entity with %fieldName = %fieldValue
.
This is my code:
private $searchCriteriaBuilder;
private $filterBuilder;
private $attributeGroupRepository;
public function __construct (
\Magento\Eav\Api\AttributeGroupRepositoryInterface $attributeGroupRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Framework\Api\FilterBuilder $filterBuilder
) {
$this->attributeGroupRepository = $attributeGroupRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->filterBuilder = $filterBuilder;
}
private function getExistingAttributeGroupIds($existingAttributeSetIds)
{
$this->searchCriteriaBuilder->addFilters(
[
$this->filterBuilder
->setField('attribute_set_id')
->setValue($existingAttributeSetIds)
->setConditionType('in')
->create(),
]
);
$attributeGroups = $this->attributeGroupRepository->getList($this->searchCriteriaBuilder->create());
$attributeGroupIds = [];
foreach ($attributeGroups->getItems() as $attributeGroup) {
$attributeGroupIds[] = $attributeGroup->getAttributeGroupId();
}
return $attributeGroupIds;
}
I did some digging around and found that the issue comes from the getList
method of the attribute group repository:
$attributeSetId = $this->retrieveAttributeSetIdFromSearchCriteria($searchCriteria);
if (!$attributeSetId) {
throw InputException::requiredField('attribute_set_id');
}
try {
$this->setRepository->get($attributeSetId);
} catch (\Exception $exception) {
throw NoSuchEntityException::singleField('attributeSetId', $attributeSetId);
}
This line $attributeSetId = $this->retrieveAttributeSetIdFromSearchCriteria($searchCriteria);
ignores the fact that my filter has the condition in
and expects it to be an integer. But based on my code it returns an array. So $this->setRepository->get($attributeSetId);
tries to retrieve an attribute set with an id that is actually an array and it obviously fails.
So I have 2 questions about this:
- Should I report this as a bug/inconsistency?
- Is there a nice way to get the attribute groups via a single query for multiple attribute sets? Please don't suggest calling
getList
for each attribute set (I have a lot of them so a foreach is not a nice solution). Please don't suggest using attribute group collections instead of repositories. I already thought about the 2 solutions above. I want a clean, "magento2-way" one.