【问题标题】:Doctrine DBAL - SELECT join two tables, with a prefix in the keys of the resultDoctrine DBAL - SELECT 连接两个表,结果的键中有前缀
【发布时间】:2015-12-16 00:01:54
【问题描述】:

我目前正在使用学说 dbal 进行数据库查询。我也在使用查询构建器。我想知道如何选择两个表并在一个数组中获取结果,该数组中的一个表的键名为前缀。

以下是所需结果的示例:

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

谢谢

【问题讨论】:

    标签: php mysql join doctrine-orm dbal


    【解决方案1】:

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

    $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)
    ;
    

    因此,要为表数据添加前缀,只需将它们声明为“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
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 2019-05-26
      • 1970-01-01
      • 2020-01-30
      • 1970-01-01
      • 1970-01-01
      • 2016-07-03
      相关资源
      最近更新 更多