[英]Fetch multi-row, single-column array using Doctrine
I have a Doctrine fetch statement like this我有一个像这样的 Doctrine fetch 语句
$query = "SELECT id FROM table LIMIT 2";
$result = $db->fetchAll($query);
which returns the array like this:它返回这样的数组:
Array
(
[0] => Array
(
[id] => 1
)
[1] => Array
(
[id] => 2
)
)
Since the only column I fetch is ID, I don't need the array scope do be that deep.由于我获取的唯一列是 ID,因此我不需要数组范围那么深。 Is there a convenient way of making Doctrine return the results in a "flat" array, similar to what what PDO does:
是否有一种方便的方法可以让 Doctrine 在“平面”数组中返回结果,类似于 PDO 的作用:
$result = $db->query($query)->fetchAll(PDO::FETCH_COLUMN);
will return会回来
Array
(
[0] => 1
[1] => 2
)
Currently I am flattening it using目前我正在使用
$result = call_user_func_array('array_merge', array_map("array_values", $result));
You can simply use the PDO functionality (at least if you have MySQL).您可以简单地使用 PDO 功能(至少如果您有 MySQL)。
$ids = $db
->executeQuery($query)
->fetchAll(\PDO::FETCH_COLUMN)
;
To resolve this problem you have to make your custom doctrine hydrator.要解决此问题,您必须制作自定义的学说水化器。
<?php
namespace MyProject\Hydrators;
use Doctrine\ORM\Internal\Hydration\AbstractHydrator;
class CustomHydrator extends AbstractHydrator
{
protected function _hydrateAll()
{
return $this->_stmt->fetchAll(PDO::FETCH_COLUMN);
}
}
<?php
$em->getConfiguration()->addCustomHydrationMode('CustomHydrator','MyProject\Hydrators\CustomHydrator');
<?php
$query = $em->createQuery('SELECT u FROM CmsUser u');
$results = $query->getResult('CustomHydrator');
I found a method called fetchFirstColumn
which appears to do this.我找到了一个名为
fetchFirstColumn
的方法,它似乎可以做到这一点。 This was probably added in a later version of doctrine.这可能是在后来的教义版本中添加的。 I am currently on Doctrine ORM 2.7.4.
我目前正在使用 Doctrine ORM 2.7.4。
I am using it like this in Symfony:我在 Symfony 中是这样使用它的:
$statement = $connection->prepare('SELECT foo FROM bar WHERE baz = :baz');
$statement->execute([':baz' => 1]);
$result = $statement->fetchFirstColumn();
The value of $result will be a numerically indexed array starting at 0 like this: $result 的值将是一个从 0 开始的数字索引数组,如下所示:
[
0 => 'foo1',
1 => 'foo2'
];
Fetch the data using fetchAssoc:使用 fetchAssoc 获取数据:
$result = $db->query($query)->fetchAssoc(PDO::FETCH_COLUMN);
You will get an Array like this:你会得到一个这样的数组:
Array (
[id] => 11
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.