【问题标题】:Doctrine 2 DQL CONCAT fields and constant stringsDoctrine 2 DQL CONCAT 字段和常量字符串
【发布时间】:2016-04-17 18:25:55
【问题描述】:

我的 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 中相同的行为?

【问题讨论】:

    标签: mysql string doctrine-orm concat


    【解决方案1】:

    显然,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")
    

    解决了问题

    【讨论】:

    • 你能分享完整的例子吗?一个错误说 Unknow column full_name。 @Subsurf
    • 很遗憾,由于我提出了这个问题,包含我最初问题的代码已从我们的代码库中删除,所以我现在无法给出示例。您的查询中一定还有其他错误。
    • 作为记录,这一点也不奇怪,因为一般的 SQL 也是如此。见:stackoverflow.com/questions/1992314/…
    • 很高兴知道,我主要使用 MySQL,它允许字符串使用双引号,所以我从不知道它不是官方 SQL 的一部分
    【解决方案2】:

    这对我有用:

    $builder->select([
       'customer.id as id',
       'customer.number as number',
       'CONCAT(CONCAT(customer.firstname, \' \'), customer.lastname) as name'
    ]);
    

    【讨论】:

      【解决方案3】:

      我在 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 的结果是

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

      希望这对某人有所帮助。在 MySQL 数据库 PDO 平台上。

      克雷格

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-17
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多