如何在Doctrine中获取像PDO :: FETCH_COLUMN这样的值? [英] How to fetch values likes PDO::FETCH_COLUMN in Doctrine?
问题描述
我有以下代码:
$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()
相同:
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)
我尝试使用execute()
,就像在某些示例中看到的那样,但它返回的结果与getArrayResult()
相同,而不是PDO语句.
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.
有什么主意吗?
推荐答案
您可以从查询结果中提取值以获得所需的数组:
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.
创建一个扩展AbstractHydrator的类:
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);
}
}
将类添加到ORM配置中:
Add the class to the ORM configuration:
$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');
这篇关于如何在Doctrine中获取像PDO :: FETCH_COLUMN这样的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!