【问题标题】:How to show generated SQL / raw SQL in TypeORM queryBuilder如何在 TypeORM queryBuilder 中显示生成的 SQL / 原始 SQL
【发布时间】:2022-06-10 16:57:14
【问题描述】:

我开发了typeormquerybuilder。出于调试的目的,我想展示生成的 SQL 查询。

我测试了printSql() 方法,但它没有显示任何 SQL 查询。

const Result = await this.attendanceRepository
  .createQueryBuilder("attendance")
  .innerJoin("attendance.child", "child")
  .select(["attendance.childId","child.class","CONCAT(child.firstName, child.lastName)"])
  .where("attendance.id= :id", { id: id })
  .printSql()
  .getOne()

console.log(Result);

它返回以下内容:

Attendance { childId: 4, child: Child { class: 'S' } }

我想要的结果是得到生成的 SQL 查询。

有什么不对的地方吗?有什么好办法获取SQL查询吗?

【问题讨论】:

    标签: sql typeorm


    【解决方案1】:

    .getQuery().getSql()

    const sql1 = await this.attendanceRepository
        .createQueryBuilder("attendance")
        .innerJoin("attendance.child", "child")
        .select(["attendance.childId","child.class","CONCAT(child.firstName, child.lastName)"])
        .where("attendance.id= :id", { id: id })
        .getQuery();
    console.log(sql1);
    
    const sql2 = await this.attendanceRepository
        .createQueryBuilder("attendance")
        .innerJoin("attendance.child", "child")
        .select(["attendance.childId","child.class","CONCAT(child.firstName, child.lastName)"])
        .where("attendance.id= :id", { id: id })
        .getSql();
    console.log(sql2);    
    

    【讨论】:

    • 还有像repo.find()这样的其他函数呢??
    【解决方案2】:

    printsql也可以用。

    
    @Module({
      imports: [
        TypeOrmModule.forRoot({
          ...options
          logging: true
        }),
      ],
    })
    
    await this.attendanceRepository
        .createQueryBuilder("attendance")
        .innerJoin("attendance.child", "child")
        .select(["attendance.childId","child.class","CONCAT(child.firstName, child.lastName)"])
        .where("attendance.id= :id", { id: id })
        .printSql();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-17
      • 2020-06-28
      • 1970-01-01
      • 2022-10-15
      • 2019-08-01
      • 2021-06-15
      相关资源
      最近更新 更多