How to Get a One-Dimensional Scalar Array as a Doctrine Dql Query Result

How to get a one-dimensional scalar array as a doctrine dql query result?

PHP < 5.5

You can use array_map, and since you only have on item per array, you can elegantly use
'current' as callback, instead of writing a closure.

$result = $em->createQuery("SELECT a.id FROM Auction a")->getScalarResult();
$ids = array_map('current', $result);

See Petr Sobotka's answer below for additional info regarding memory usage.

PHP >= 5.5

As jcbwlkr's answered below, the recommended way it to use array_column.

How to get an aggregate scalar result from Doctrine and Symfony?

The answer is that I had the parameter for semester_id hard coded to 14 and bound a parameter that did not match. Change

c2_.semester_id = 14

to

c2_.semester_id = :semester_id

Gives:

[0] Person
[1] Application plus scalar entries.

Doctrine return only one parameter of the related entity

Currently solved this by editing the getInvalidPrice getter:

public function getInvalidPrice(): ?int
{
return $this->invalidPrice ? $this->invalidPrice->getHasInvalidPrice(): null;
}

I return the hasInvalidPrice property instead of the whole invalidPrice object.

Get flat array when making mutliple selects in Doctrine

From the DQL above seems like you end up with mixed results and that's Doctrine default behavior when using $qB->getQuery()->getResult().

SELECT u, p.quantity FROM Users u...

Here, the result will again be an array of arrays, with each element
being an array made up of a User object and the scalar value
p.quantity.

I would try to debug the SQL generated and if I am right then there is your why. IMHO this behavior can not be changed but maybe I am wrong.

In this case the solution could be write a protected PHP function for flatten the array as you want to.

Update:

I haven't tried but seems to be possible to use Doctrine Events to achieve this. There is not built-in Events for preSelect or postSelect however you can create your own Event and register it properly so you can call it at any point. As said before I didn't tried and I am not sure at all that this is possible using any Event (I might be wrong).

Just a side note, I would not try to over complicate this to much, you are adding a layer of complexity to the entity when you can do this easily on your controller by creating a private|public function that you can reuse at any point.

More info:

  • DQL Select Results


Related Topics



Leave a reply



Submit