0

我的正常查询是这样的。

$qb = $placeRepository->createQueryBuilder('p');
var_dump($qb->getQuery()->getResult());

作为对象,我会得到很少的结果。所以这是正常的行为。

然后我想添加一个自定义字段ResultSetMapping

$qb = $placeRepository->createQueryBuilder('p');
$qb->addSelect('123 as distance');

$rsm = new ResultSetMapping;
$rsm->addEntityResult(Place::class, 'p');
$rsm->addFieldResult('p', 'id', 'id');
$rsm->addScalarResult('distance', 'distance');

var_dump($qb->getQuery()->setResultSetMapping($rsm)->getResult());

随着ResultSetMappingBuilder它也不起作用。

$qb = $placeRepository->createQueryBuilder('p');
$qb->addSelect('123 as distance');

$rsm = $placeRepository->createResultSetMappingBuilder('p');

var_dump($qb->getQuery()->setResultSetMapping($rsm)->getResult());

不工作意味着:其中包含零项的数组。

4

1 回答 1

0

好的,找到了。但没有像我想要的那样工作

/** @var \Doctrine\ORM\EntityManager $em */
$em = $this->getDoctrine()->getManager();

// Working but bad because defining all by yourself
$rsm = new ResultSetMapping();
$rsm->addEntityResult(Place::class, 'p');
$rsm->addFieldResult('p','p_id','id');

// Good
$rsmB = new ResultSetMappingBuilder($em);
$rsmB->addRootEntityFromClassMetadata(Place::class, 'p');
// Not working because separate field
//$rsmB->addScalarResult('distance', 'distance');
// Not working because not found ... (not a @ORM\Column)
$rsmB->addFieldResult('p', 'distance', 'distance');

我添加了评论为什么它不起作用。

现在我要循环

于 2020-11-17T17:28:27.927 回答