TypeORM 选择列名的别名 [英] TypeORM select alias of column name

查看:44
本文介绍了TypeORM 选择列名的别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

this.sampleRepo.find (
            {
                
                order: {
                    id: "DESC"
                },
                select: ['id','group']
                
                
            }

    );

这会按预期返回 id 和 group,但是如何将 id 作为 user_id 返回?以及如何从组中选择不同的值?

this returns the id and group as expected, but how to return id as user_id ? and also how to select distinct values from group?

推荐答案

只需在选择字符串中添加别名,例如:

Just add an alias in you select string, e.g.:

select: ['id AS user_id','group AS user_group']


如果前一个选项不起作用,它应该在 queryBuilder 中起作用:


If the previous option didn't work, it should work in queryBuilder:

this.sampleRepo
      .createQueryBuilder('user')
      .orderBy('user.id', 'DESC')
      .select(['id AS user_id','group AS user_group'])
      .getRawMany() // or .getMany()


我已经用我的一个例子做了你需要的事情 (这里的最后一个) 但写了这个(更新.用 getRawMany 和 distinct 修复):

getMany(): Promise<UserEntity[]> {
    return this.userRepo.createQueryBuilder('user')
      .where({ username: 'breckhouse0' })
      .select(['DISTINCT (user.username) AS user_name', 'user.id AS user_id'])
      .getRawMany();
  }

这如您所愿 - 结果

这篇关于TypeORM 选择列名的别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆