如何在Typeorm querybuilder中编写特定的原始查询

时间:2020-10-18 08:07:04

标签: mysql sql typeorm

开发应用程序时,我开发了typeorm querybuilder,旨在获取attendance数据和child数据。

当我设置以下查询构建器时。

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

我遇到了以下错误。

似乎child.lastName没有定义。

当我看到querybuilder生成的sql时,以下是问题的原因。

CONCAT(`child`.`first_name`,child.lastName) 

有什么好办法解决这个问题吗?

我应该在哪里修复?

 code: 'ER_BAD_FIELD_ERROR',
api-server    |   errno: 1054,
api-server    |   sqlMessage: "Unknown column 'child.lastName' in 'field list'",
api-server    |   sqlState: '42S22',
api-server    |   index: 0,
api-server    |   sql: "SELECT `attendance`.`child_id` AS `attendance_child_id`, `attendance`.`id` AS `attendance_id`, `child`.`class` AS `child_class`, `child`.`id` AS `child_id`, CONCAT(`child`.`first_name`,child.lastName) as 'childName' FROM `attendances` `attendance` INNER JOIN `children` `child` ON `child`.`id`=`attendance`.`child_id` WHERE ( `attendance`.`id`= '5' ) AND ( `attendance`.`deleted_at` IS NULL )",
api-server    |   query: "SELECT `attendance`.`child_id` AS `attendance_child_id`, `attendance`.`id` AS `attendance_id`, `child`.`class` AS `child_class`, `child`.`id` AS `child_id`, CONCAT(`child`.`first_name`,child.lastName) as 'childName' FROM `attendances` `attendance` INNER JOIN `children` `child` ON `child`.`id`=`attendance`.`child_id` WHERE ( `attendance`.`id`= ? ) AND ( `attendance`.`deleted_at` IS NULL )",
api-server    |   parameters: [ '5' ]

如果有人有意见,请告诉我。

谢谢

1 个答案:

答案 0 :(得分:0)

问题来自您的 sql 查询

SELECT `attendance`.`child_id` AS `attendance_child_id`, `attendance`.`id` AS `attendance_id`, `child`.`class` AS `child_class`, `child`.`id` AS `child_id`, CONCAT(`child`.`first_name`,child.lastName) as 'childName'
FROM `attendances` `attendance`
INNER JOIN `children` `child` ON `child`.`id`=`attendance`.`child_id`
WHERE ( `attendance`.`id`= '5' ) AND ( `attendance`.`deleted_at` IS NULL )

postgresql ignores case by default,所以 child.lastName 变成了不存在的 child.lastname

您需要做的是将列名放在双引号之间:child.lastName => child."lastName"

应用于您的 typeorm 代码:​​

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