为什么Doctrine QueryBuilder会破坏我的查询? [英] Why does Doctrine QueryBuilder destroy my query?
问题描述
我正在尝试在表格中收到最新的 id
。因此,我创建了一个静态类,以便从任何所需的表中获取最新的 id
。
I am trying to receive the latest id
in a table. Therefore I created a static class to be able to fetch this latest id
from any desired table.
public static function getLatestId($entityManager, $table, $column) {
$qb = $entityManager->createQueryBuilder();
$qb->select('t.'.$column)->from($table, 't')
->orderBy('t.'.$column, 'DESC')->setMaxResults(1);
$query = $qb->getQuery();
$result = $query->getSingleResult();
$latestId = $result[$column];
return $latestId;
}
当我调用函数例如使用 getLatestId($ em,'company','companyId')
并检查查询(使用 getQuery()
它创建了奇怪的声明:
When I call the function e.g. with getLatestId($em, 'company', 'companyId')
and check the query (with getQuery()
, it creates weird statement:
SELECT c0_.companyId AS companyId0 FROM company c0_
ORDER BY c0_.companyId DESC LIMIT 1
为什么要将 t。
到列? c0 _。
,后缀为<?c $ c> 0
Why does it replace the t.
by c0_.
and suffixes a 0
to the column?
推荐答案
首先你要检索一个部分,默认情况下会返回一个标量变量,所以为了清楚起见,使用getSingleScalarResult()方法是很好的参见: http://docs.doctrine-project.org/en/latest/reference/partial-objects。 html
First you are retreiving a partial, which will return a scalar variable by default. So for clarity it's good to use the getSingleScalarResult() method. See also: http://docs.doctrine-project.org/en/latest/reference/partial-objects.html
然后你试图读取userId列,但是你传递了companyId列,所以替换这个:
Then you are trying to read the userId column, but you passed the companyId column. So replace this:
$latestId = $result['userId'];
与此:
$latestId = $result[$column];
不要担心别名给你的列的别名。这是正常的行为,它有助于Doctrine在内部映射一切正确的方式。
Don't worry about the aliases Doctrine gives to your columns. This is normal behaviour and it helps Doctrine to map everything the right way internally.
这篇关于为什么Doctrine QueryBuilder会破坏我的查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!