spacecodeur
spacecodeur

Reputation: 2406

Symfony 4, findAll with entity's property as array key

From symfony 4, when I use the method findAll I get an associative array of my entity's objects, where each key is one an object of my entity

I am looking for a pretty way to get instead an associative array where the key is the value of a specific field of my entity, and the value the object of my entity.

In practical terms, when I use findAll I get this :

Array
(
    [0] => App\Entity\Foo Object
        (
            [id:App\Entity\Foo:private] => 1
            [name:App\Entity\Foo:private] => nameValue1
        )

    [1] => App\Entity\Foo Object
        (
            [id:App\Entity\Foo:private] => 2
            [name:App\Entity\Foo:private] => nameValue2
        )

    [2] => App\Entity\Foo Object
        (
            [id:App\Entity\Foo:private] => 3
            [name:App\Entity\Foo:private] => nameValue3
        )
        ...
)

But, instead, I want this :

Array
(
    ["nameValue1"] => App\Entity\Foo Object
        (
            [id:App\Entity\Foo:private] => 1
            [name:App\Entity\Foo:private] => nameValue1
        )

    ["nameValue2"] => App\Entity\Foo Object
        (
            [id:App\Entity\Foo:private] => 2
            [name:App\Entity\Foo:private] => nameValue2
        )

    ["nameValue3"] => App\Entity\Foo Object
        (
            [id:App\Entity\Foo:private] => 3
            [name:App\Entity\Foo:private] => nameValue3
        )
        ...
)

Upvotes: 5

Views: 4482

Answers (1)

iiirxs
iiirxs

Reputation: 4582

To get this functionality you have to implement your own function in the repository of Foo class and use QueryBuilder's indexBy() :

<?php

namespace App\Repository;
use Doctrine\ORM\EntityRepository;

class FooRepository extends EntityRepository
{

    public function findAllIndexed()
    {
        $qb = $this->createQueryBuilder('foo');
        $query = $qb->indexBy('foo', 'foo.name')->getQuery();
        return $query->getResult();
    }
}

Now you just call $repository->findAllIndexed() instead of $repository->findAll() function.

Upvotes: 9

Related Questions