Reputation: 1927
I want this function
$entityManager
->getRepository('AppBundle:Example')
->findBy(array('id' => $id, 'active' => true));
to return an associative array of Example objects with ID as keys. For example:
array(
'100' => 'Example object 1',
'135' => 'Example object 2'
)
I can achieve this using foreach
after retrieving the data, but I'd like to know if there is a proper way to do this.
Upvotes: 2
Views: 4150
Reputation: 8355
You need to set up a custom method in your Repository, and there you can pass a second parameter to createQueryBuilder()
, like this:
public function findActiveObjectsIndexedById(): array
{
return $this->createQueryBuilder('o', 'o.id')
// ...
->getQuery()
->getArrayResult();
}
I just learned this from https://stackoverflow.com/a/51689187/1668200 and couldn't find any better documentation than https://www.doctrine-project.org/api/orm/latest/Doctrine/ORM/QueryBuilder.html#method_indexBy
Upvotes: 5
Reputation: 2167
What you need for doing what you're suggesting, would be to define your own Custom Hydrator. This allows you to define the logic on how to prepare the result after fetching it from the storage engine.
But before going that route, I think you should ask yourself: What's the use case that desperately needs introducing another layer of complexity to my application in order to get the result in a particular way directly from the database? Do you have critical performance requirements? If so, please go ahead with the custom hydrator. Otherwise, just map your results from the objects into the desired structure before returning it, encapsulate that logic into its own class and unit test it.
If you want to skip the hydration into objects step completely, simply fetch the results directly into an array with $query->getArrayResult()
.
Upvotes: 1