如何使用 typeorm 在 NestJS 框架上执行原始 SQL 查询

4 postgresql typeorm nestjs

我将使用 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'
Run Code Online (Sandbox Code Playgroud)

Jay*_*iel 13

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

const rawData = await connection.query(`SELECT * FROM USERS`);
Run Code Online (Sandbox Code Playgroud)

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

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

  async doSomeQuery() {
    return this.connection.query('SELECT * FROM USERS;');
  }
}
Run Code Online (Sandbox Code Playgroud)

从 Nest v9 开始(以及 @nestjs/typeorm@8 中的某个位置,在版本的后期),使用了 TypeORM v0.3.0,但@InjectConnection()已弃用。@InjectDataSource()应该使用

  • @JayMcDoniel 等人。`@InjectConnection()` 装饰器现已弃用。现在使用“@InjectDataSource()”。 (2认同)