Doctrine 2 DQL CONCAT 字段和常量字符串

9

我在MySQL表中有firstnamelastname字段。为了方便起见,我希望给我的Doctrine 2实体添加一个计算列full_name。在普通的MySQL中,我会这样做:

SELECT CONCAT(firstname, " ", lastname) AS full_name FROM customers;

然而,使用Doctrine的CONCAT实现时,连接字段和常量字符串(在这种情况下是“ ”)似乎不起作用。当使用以下代码时:

$repository
    ->createQueryBuilder('customer')
    ->select('CONCAT(customer.firstname, " ", customer.lastname) AS full_name')
    // ...

我遇到了错误

[Syntax Error] line 0, col 91: Error: Expected StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression, got '"'

如何在MySQL中实现相同的行为?
3个回答

42

显然,DQL 中的字符串只能用单引号而不是双引号括起来。在文档中进行简要搜索并没有直接提到这种行为,但我注意到所有包含常量字符串的示例都使用了单引号。

更改

->select('CONCAT(customer.firstname, " ", customer.lastname) AS full_name')

->select('CONCAT(customer.firstname, \' \', customer.lastname) AS full_name')
或者
->select("CONCAT(customer.firstname, ' ', customer.lastname) AS full_name")

解决了问题


你能分享一下完整的例子吗?错误提示为未知列 full_name。@Subsurf - Ali Emre Çakmakoğlu
很遗憾,自从我提出这个问题后,包含我最初问题的代码已经从我们的代码库中删除,所以我现在无法举例说明。你的查询中一定有其他错误。 - Subsurf
值得一提的是,这一点并不令人惊讶,因为同样适用于SQL。参见:https://dev59.com/-nI-5IYBdhLWcg3wKE6x - jlh
很好知道,我主要使用MySQL来处理字符串,因为它允许使用双引号,所以我从未意识到它不是官方SQL的一部分。 - Subsurf

3
这对我有效:
$builder->select([
   'customer.id as id',
   'customer.number as number',
   'CONCAT(CONCAT(customer.firstname, \' \'), customer.lastname) as name'
]);

1

我在Doctrine 2.4+中使用的解决方案:

$concat = new Query\Expr\Func('CONCAT', $name[$k]);
$concat .= ' as ' . $k;
$concat = str_replace(',', ',\' \',', $concat);
$this->query->addSelect($concat);

$name[$k]是一个包含任意数量字段的数组。我使用str_replace在字段之间添加了一些空格。$k是连接字段的名称,所以$concat的结果为

"CONCAT(p.email,' ', h.phoneNumber,' ', p.officialName) as details"

希望这能帮助到一些人。关于MySQL数据库PDO平台。 克雷格

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接