doctrine does not hydration when select custom fields

1.9k views Asked by At

i have tried select fields with doctrine query buidler.

$queryBuilder = $entityManager->createQueryBuilder();
$queryBuilder->select('au.id, au.firstName')
    ->from('Api\V1\Entity\AgencyUser', 'au')
    ->orderBy('au.firstName', 'asc');
$queryBuilder->andWhere('au.agency = :agencyId')
    ->setParameter('agencyId', $agency->getId());

print_r($queryBuilder->getQuery()->getResult(Query::HYDRATE_OBJECT));exit;

result :

Array
(
    [0] => Array
    (
        [id] => 1
        [firstName] => agency
    )

)

why this is an array ? i want to hydrated result. any idea ?

1

There are 1 answers

0
Logan Bailey On BEST ANSWER

You want to use Doctrine's Partial Object Syntax

$queryBuilder->select('partial au.{id, firstName}')

As to why it's not returning an object, this is from the same documentation linked above:

By default when you run a DQL query in Doctrine and select only a subset of the fields for a given entity, you do not receive objects back. Instead, you receive only arrays as a flat rectangular result set, similar to how you would if you were just using SQL directly and joining some data.