Sometimes you need to fetch many records with Doctrine and deal with them as required. It often happens in batch processes so your resulting variable would hold many big objects in it which is not a good idea. On top of that, your query would be slow as well because you're selecting objects and maybe associated objects too. This will have a performance impact in your application. To solve this performance issue, you can select just ID of all the records you need and then use Reference Proxies to obtain a reference to the relevant entity itself. Check example below to how it is done.


Repository


class UserRepository extends EntityRepository
{
public function findManyByPostcodes(array $postcodes)
{
$q = $this->createQueryBuilder('u')
->where('u.postcode IN (:postcodes)')
->setParameter('postcodes', array_values($postcodes));

return $q->getQuery()->getResult(Query::HYDRATE_SIMPLEOBJECT);
}
}

Repository request and response


# Request
findManyByPostcodes(['AB1 BA1', 'UB3 3BU'])

# Response
array(
0 => 15,
1 => 19,
2 => 22,
3 => 45
}

Service


class UserService
{
public function doSomething()
{
$users = $this->userRepository->findManyByPostcodes(['AB1 BA1', 'UB3 3BU']);

foreach ($users as $id) {
$user = $this->getUserReference($id);
// .. Persist, Flush, Remove etc
}
}

private function getUserReference($id)
{
return $this->entityManager->getReference('My\TestBundle\Entity\User', $id);
}
}