0

My normal query was looking like this.

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

I'll get few results as objects. So this is the normal behaviour.

Then I want to add a custom field with 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());

With a ResultSetMappingBuilder its also not working.

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

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

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

Not working means: Array with zero items in it.

yivi
  • 42,438
  • 18
  • 116
  • 138
Patrick
  • 829
  • 2
  • 13
  • 34

1 Answers1

0

Ok found it. But not working like I want

/** @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');

I added comments why its not working.

Now I'm going to loop

Patrick
  • 829
  • 2
  • 13
  • 34
  • try this `var_dump($qb->getQuery()->select($rsmB->generateSelectClause())->setResultSetMapping($rsm)->getResult());` – axon Dec 12 '20 at 13:26