Kik Minev
Kik Minev

Reputation: 113

Get symfony doctrine findAll to return array with specific type of keys

I'm looking for elegant way to restructure the array returned by Symfony findAll with specific keys. For instance If I have an entity Animal with fields id, name, color etc. I would like to make a repository method that returns an array with all animals and the key for each one to be the 'name' field so I can make lookups in this array. The way I'm doing it now is by iterating the array and creating a new one, but I'm wondering if there is something ready made that I can use?

Upvotes: 1

Views: 9028

Answers (2)

revengeance
revengeance

Reputation: 891

No there is a thing built-in doctrine, which is called index by, I also didn't know that for long time. Check code examples :).

By using function getAllLocationsAssoc, it will return associative array indexed by location.id. So the keys of array will be the id's of objects in db. You can use it like second parameter in createQueryBuilder function.

class LocationRepository extends EntityRepository
{
    /**
     * @return array
     */
    public function getAllLocationsAssoc(): array
    {
        return $this->createQueryBuilder('location', 'location.id') 
            ->getQuery()
            ->getArrayResult();
    }

}

Another option is to specify as third parameter in ->from qb function.

<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
/**
 * Class CityRepository
 * @package AppBundle\Repository
 */
class CityRepository extends EntityRepository
{
    /**
     * @return array
     */
    public function getAllCitiesAssoc(): array
    {
        return $this->_em->createQueryBuilder()
            ->select('c')
            ->from('AppBundle:City', 'c', 'c.name') // Third parameter is index-by
            ->getQuery()
            ->getResult();
    }
}

Upvotes: 9

iiirxs
iiirxs

Reputation: 4582

No there is nothing like that built-in by doctrine. However, instead of iterating the array which is somewhat ugly, if the returned array is an array of entity objects, you could do something like this to get the names of the animals:

$names = array_map(function($animal) { return $animal->getName(); }, $arrayOfAnimals);

If the returned array is an array of arrays you could simple do that to get animals names (in case you use doctrine HYDRATE_ARRAY hydration):

$names = array_column($arrayOfAnimals, 'name');

Then you could simple use this to get your final array:

$finalArrayOfAnimals = array_combine($names, $arrayOfAnimals);

Upvotes: 2

Related Questions