当 select 个自定义字段时,学说不会水合

doctrine does not hydration when select custom fields

我已经尝试 select 带有学说查询构建器的字段。

$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;

结果:

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

)

为什么这是一个数组?我想要补水效果。有什么想法吗?

您想使用 Doctrine 的 Partial Object Syntax

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

至于为什么它不返回对象,这来自上面链接的同一文档:

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.