What is the recommended way to get a Shopware 6 entity by ID?

Viewed 607

I have a entity ID and want to get the Entity object via repository, currently we do

$criteria = new Criteria();
    $criteria->addFilter(new EqualsFilter('id', $propertyId));

    $property = $this->propertyGroupOptionRepository->search(
        $criteria,
        $this->context
    )->first();

    if($property) {
        return $property->get('groupId');
    }

Is there a nicer way, like Laravel's find method?

2 Answers

As you already mentioned in your own answer you can pass the IDs as a parameter to the Criteria object.

I suggest $property = $this->propertyGroupOptionRepository->search(new Criteria([$propertyId]), $context)->first()

A find method isn't implemented and I assume never will, cause you may want to load use some associations and/or aggragations.

It is at least possible to create a criteria with an ID filter without creating an Equals filter.

The shopware core does it like this:

$product = $this->productRepository->search(new Criteria([$productId]), $context)->get($productId);

So for the above example it would be

$property = $this->propertyGroupOptionRepository
    ->search(new Criteria([$propertyId]), $context)->get($propertyId);
Related