首页 > 解决方案 > 如何使用 typeorm 在 NestJS 框架上执行原始 SQL 查询

问题描述

我将使用 Typeform 在 NestJS 框架上执行这么长的查询。请让我知道如何执行此查询。

select user.id, user.fullName, (select count(*) sendCnt from chat where senderId = user.id), (select count(*) recvCnt from chat where receiverId = user.id) from users user where user.role = 'Admin'

标签: postgresqlnestjstypeorm

解决方案


如果您正在使用,您可以使用和使用TypeORM注入连接来运行原始查询,如TypeORM 文档中所示@InjectConnection()query

const rawData = await connection.query(`SELECT * FROM USERS`);

假设你使用@nestjs/typeorm,this.connection可以通过@InjectConnection()构造函数中的装饰器获取

@Injectable()
export class FooService {
  constructor(@InjectConnection() private readonly connection: Connection) {}

  async doSomeQuery() {
    return this.connection.query('SELECT * FROM USERS;');
  }
}

推荐阅读