hardy123480
hardy123480

Reputation: 155

Access properties of Entities

I'm getting all active countries via the service id country.repository

public function getCountries(Context $context): EntityCollection
{
    $criteria = new Criteria();
    $criteria->addFilter(new EqualsFilter('active', true));

    return $this->countryRepository->search($criteria, $context)->getEntities();
}

This gives me this CountryCollection: CountryCollection

How can I access each element to get the id and the name?

I tried to loop over

public function test($context): array
{
    $countryIds = $this->getCountries($context);

    $ids = [];
    foreach ($countryIds as $countryId) {
        $ids[] = $countryId['id'];
    }
    return $ids;
}

Obviously this doesn't work. It gives this error:

Cannot use object of type Shopware\Core\System\Country\CountryEntity as array

Upvotes: 1

Views: 420

Answers (2)

j_elfering
j_elfering

Reputation: 3190

If you are only interested in the ids of the countries you can use

$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('active', true));

$ids = $this->countryRepository->searchIds($criteria, $context)->getIds();

searchIds() will only return the ids of the entities and not all of their properties, the benefit is that not all values have to be loaded from the DB and hydrated, therefore searchIds() is faster then the normal search().

Upvotes: 2

Stone Vo
Stone Vo

Reputation: 119

You need to call the function like this

public function test($context): array
{
    $countries = $this->getCountries($context);
    $ids = [];
    foreach ($countries as $country) {
        $ids[] = $country->getId();//or $country->getName()
    }
    return $ids;
}

Usually you need to open the entity file. In your case it is CountryEntity.php to check the function to get the id or other fields there.

Upvotes: 0

Related Questions