Doctrine DBAL - SELECT 连接两个表,在结果的键中有一个前缀

Doctrine DBAL - SELECT join two tables, with a prefix in the keys of the result

我目前正在使用 doctrine dbal 进行数据库查询。我也在使用查询生成器。我想知道如何 select 两个表并在一个数组中获取结果,该数组具有已连接的其中一个表的键名前缀。

这是所需结果的示例:

$data   = [
    key1 => 'value1',
    key2 => 'value2',
    key3 => 'value3',
    key4 => 'value4',
    table2.key1 => 'value1',
    table2.key2 => 'value2',
    table2.key3 => 'value3',
]

谢谢

我刚遇到同样的问题,我用下面的方法解决了它:

$result = $this->createQueryBuilder('comments')
        ->select([
            'comments.id as id',
            'comments.post_id as postId',
            'comments.userId as userId',
            'comments.userName as userName',
            'comments.userEmail as userEmail',
            'comments.parentId as parentId',
            'comments.postedAt as postedAt',
            'comments.status as status',
            'comments.comment as comment',
            'user.fullname as user_userName',
            'user.email as user_email',
       ])
       ->leftJoin(
              'Entity\User', 'user',
              Query\Expr\Join::WITH,
              'comments.userId = user.id'
      )
      ->where('comments.post_id=:postId')->setParameter('postId', $postId)
      ->getQuery()
      ->getResult(Query::HYDRATE_ARRAY)
;

因此,要为 table 数据添加前缀,只需将它们声明为 "select" 语句为

table.var1 as prefix_var1, table.var2 as prefix_var2

结果将是

[
    prefix_var1 => value,
    prefix_var2 => value,
]

当您将 select 声明为:

时,您还可以做一件事
table1, table2.var1 as prefix_var1, table2.var2 as prefix_var2

你会得到下一个结果

[
    0 => [ // it's come from table1
           var1 => value,  
           var2 => value,
    ],
    prefix_var1 => value, // it's come from table2
    prefix_var2 => value, // it's come from table2
]