Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine ORM query builder fetch key value pair

I have the following code in an entity repository:

$rows = $this->createQueryBuilder('t')
    ->select(['t.idColumn', 't.valueColumn'])
    ->where('t.foo = :foo')
    ->orderBy('t.idColumn', 'ASC')
    ->setParameter('foo', $foo)
    ->getQuery()
    ->getArrayResult(); // This returns [[idColumn => ..., valueColumn => ...], ...]
$data = [];

foreach ($rows as $row) {
    $data[$row['idColumn']] = abs($row['valueColumn']); // Remapping to [id => value]
}

return $data;

Is there any way to get rid of the custom remapping natively? I know that you can use the indexBy parameter, but that only gets me the correct keys but not values.

P.S. I know of array_column(), but that's an extra step that I have to make every time, not to mention it doesn't work on methods that entities have.

P.P.S. This is not using Symfony.

like image 913
jurchiks Avatar asked Aug 29 '26 07:08

jurchiks


1 Answers

It does not appear this is a feature implemented in the QueryBuilder, however fetchAllKeyValue was added in DBAL 2.11 to the Connection object.

Commit, usage

like image 147
Optimum Avatar answered Aug 30 '26 22:08

Optimum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!