How to fetch values likes PDO::FETCH_COLUMN in Doc

2019-05-21 06:14发布

I have the following code:

$repository = $this->entitymanager->getRepository('Intlist\Entity\Location');
$query = $repository->createQueryBuilder('l')
    ->select('l.country')
    ->groupBy('l.country')
    ->where('l.country != :empty_country')
    ->setParameter('empty_country', "")
    ->getQuery();

And I would like to obtain something like [ 'EN', 'FR', 'US' ], like PDO::FETCH_COLUMN would return. I tried getScalarResult() but it returns the same result as getArrayResult():

array (size=2)
  0 => 
    array (size=1)
      'country' => string 'DE' (length=2)
  1 => 
    array (size=1)
      'country' => string 'MM' (length=2)

I tried to use execute() as I have seen on some examples but it returns the same result as getArrayResult() and not a PDO statement.

Any idea?

1条回答
小情绪 Triste *
2楼-- · 2019-05-21 06:45

You can extract values from your query result to get the array you want :

$repository = $this->entitymanager->getRepository('Intlist\Entity\Location');
$query = $repository->createQueryBuilder('l')
    ->select('l.country')
    ->groupBy('l.country')
    ->where('l.country != :empty_country')
    ->setParameter('empty_country', "")
    ->getScalarResult();

$country_codes = array();
foreach($query as $result){
    $country_codes[] = $result['country'];
}

If you want native results, you can make a custom hydration mode, as explained in Doctrine doc.

Create a class extending AbstractHydrator:

namespace MyProject\Hydrators;

use Doctrine\ORM\Internal\Hydration\AbstractHydrator;

class ColumnHydrator extends AbstractHydrator
{
    protected function _hydrateAll()
    {
        return $this->_stmt->fetchAll(PDO::FETCH_COLUMN);
    }
}

Add the class to the ORM configuration:

$em->getConfiguration()->addCustomHydrationMode('ColumnHydrator', 'MyProject\Hydrators\ColumnHydrator');

Then use it:

$repository = $this->entitymanager->getRepository('Intlist\Entity\Location');
$query = $repository->createQueryBuilder('l')
    ->select('l.country')
    ->groupBy('l.country')
    ->where('l.country != :empty_country')
    ->setParameter('empty_country', "")
    ->getQuery();
$results = $query->getResult('ColumnHydrator');
查看更多
登录 后发表回答