You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除TypeORM QueryBuilder返回字段的attendance_前缀?

解决TypeORM QueryBuilder返回字段带attendance_前缀的问题

嘿,我明白你遇到的困扰了——用getRawOne()返回的结果里,attendance表的字段都带了attendance_前缀,和你期望的格式不符。下面给你两种简单可行的解决方案:

方案一:手动映射返回结果

这是最直接的方式,拿到原始结果后,自己处理字段名,去掉前缀:

const rawResult = await this.attendanceRepository
 .createQueryBuilder("attendance")
 .leftJoin("attendance.child", "child")
 .select("attendance")
 .addSelect("CONCAT_WS(' ', child.firstName, child.middleName, child.lastName)", "childName")
 .addSelect("child.class")
 .where("attendance.id= :id", { id: id})
 .getRawOne();

// 手动映射字段,移除attendance_前缀
const result = {};
for (const [key, value] of Object.entries(rawResult)) {
  if (key.startsWith('attendance_')) {
    result[key.replace('attendance_', '')] = value;
  } else {
    result[key] = value;
  }
}

console.log(result); // 这就是你期望的格式

方案二:手动指定attendance字段的别名

如果你不想事后处理,可以修改QueryBuilder,不使用select("attendance"),而是逐个指定attendance的字段并设置别名,这样生成的SQL就不会自动加前缀了:

const result = await this.attendanceRepository
 .createQueryBuilder("attendance")
 .leftJoin("attendance.child", "child")
 // 逐个指定attendance的字段,设置别名去掉前缀
 .addSelect("attendance.id", "id")
 .addSelect("attendance.child_id", "child_id")
 .addSelect("attendance.attendance_cd", "attendance_cd")
 .addSelect("attendance.come_home_time", "come_home_time")
 .addSelect("attendance.late_time", "late_time")
 .addSelect("attendance.memo", "memo")
 .addSelect("attendance.created_at", "created_at")
 .addSelect("attendance.updated_at", "updated_at")
 .addSelect("attendance.deleted_at", "deleted_at")
 // 保留你自定义的字段
 .addSelect("CONCAT_WS(' ', child.firstName, child.middleName, child.lastName)", "childName")
 .addSelect("child.class", "child_class")
 .where("attendance.id= :id", { id: id})
 .getRawOne();

这样生成的SQL里,attendance的字段就会直接用你设置的别名(比如id而不是attendance_id),返回的结果自然就是你想要的格式啦。

两种方案里,方案一适合字段较多的情况,不用逐个写字段;方案二则更直接,生成的SQL更贴合你的需求,看你自己的场景选择就行。

内容的提问来源于stack exchange,提问作者Heisenberg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 16:37:41