如何在Doctrine中获取像PDO :: FETCH_COLUMN这样的值?

时间:2015-01-07 15:30:07

标签: pdo doctrine-orm

我有以下代码:

$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();

我想获得像[ 'EN', 'FR', 'US' ]这样的东西,就像PDO::FETCH_COLUMN会回来一样。我尝试了getScalarResult(),但它返回与getArrayResult()相同的结果:

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

我尝试使用execute(),就像我在一些示例中看到的那样,但它返回的结果与getArrayResult()相同,而不是PDO语句。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您可以从查询结果中提取值以获取所需的数组:

$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'];
}

如果您想要原生结果,可以进行自定义保湿模式as explained in Doctrine doc

创建一个扩展AbstractHydrator的类:

namespace MyProject\Hydrators;

use Doctrine\ORM\Internal\Hydration\AbstractHydrator;

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

将类添加到ORM配置:

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

然后使用它:

$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');