Php 选择一个ID数组
我正在尝试查询ID数组,希望得到如下结果: 数组(1,2,3,4,5,6,7) 但我得到的是 数组(数组('id'=>1),数组('id'=2)) 我正在使用的查询如下所示:Php 选择一个ID数组,php,symfony,doctrine-orm,Php,Symfony,Doctrine Orm,我正在尝试查询ID数组,希望得到如下结果: 数组(1,2,3,4,5,6,7) 但我得到的是 数组(数组('id'=>1),数组('id'=2)) 我正在使用的查询如下所示: $qb = $this->createQueryBuilder('b') ->select('b.id') ->where('b.game = :gID') ->setParameter('gID', $game->g
$qb = $this->createQueryBuilder('b')
->select('b.id')
->where('b.game = :gID')
->setParameter('gID', $game->getId());
return $qb->getQuery()->getResult();
达到预期效果的最佳方式是什么。由于此查询将加载多达50万个ID,因此它也应该是性能良好的。您可以使用array\u map函数将行映射到平面数组:
var_dump(
array_map(
function($element) {
return $element['id'];
}, array(array('id' => 1), array('id' => 2))
)
);
结果:
array(2) {
[0]=>
int(1)
[1]=>
int(2)
}
默认情况下这是不可能的。信条有可能是为了实现像你这样的目标而写的。因此,您必须编写自定义水合模式:
#app/config/config.yml
doctrine:
orm:
...
entity_managers:
default:
auto_mapping: true
hydrators:
MyHydrator: App\YourBundle\Hydrators\MyHydrator
水合器:
// App\YourBundle\Hydrators\MyHydrator.php
namespace App\YourBundle\Hydrators;
use Doctrine\ORM\Internal\Hydration\AbstractHydrator;
use \PDO;
class MyHydrator extends AbstractHydrator
{
protected function hydrateAllData()
{
$result = array();
$cache = array();
foreach($this->_stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$this->hydrateRowData($row, $cache, $result);
}
return $result;
}
protected function hydrateRowData(array $row, array &$cache, array &$result)
{
if(count($row) == 0) {
return false;
}
$result[] = $row['id0'];
}
}
并简单地使用:
$results = $this->getDoctrine()->getManager()
->createQuery('{yourQuery}')->getResult('MyHydrator');
或者,在您的实体存储库中:
$qb = $this->createQueryBuilder('b')
->select('b.id')
->where('b.game = :gID')
->setParameter('gID', $game->getId());
return $qb->getQuery()->getResult('MyHydrator');
更多信息。感谢我提出的解决方案。我想也许我可以直接从条令中得到它。不幸的是,你从db中得到的是一组行(数组)而不是一组标量,即使你的投影选择了单列。他应该编写自定义模式。请看我的答案。