Knex Id 列被加入的 table id 覆盖

Knex Id Column overwritten by joined table id

我有一个 REST API 端点,returns 一个内部连接记录集定义如下:

const getByRecipeId = recipeId => {
  return knex("recipe_details")
    .innerJoin("jobs", "jobs.id", recipe_details.id_job")
    .where("id_recipe", recipeId)
}

在调试中我有以下 sql 语句 (Postgres):

select
    *
from
    "recipe_details"
inner join "jobs" on
    "jobs"."id" = "recipe_details"."id_job"
where
    "id_recipe" = 1

那个returns这个记录集

id|id_recipe|seq|id_job|qty_time|qty_job|id|code|description|
--|---------|---|------|--------|-------|--|----|-----------|
 1|        1| 10|     1|      10|     24| 1|job1|job descr1 |
 3|        1| 30|     2|      15|     24| 2|job2|job descr2 |
13|        1| 50|     3|      50|     15| 3|job3|job descr3 |
 2|        1| 20|     3|       5|     30| 3|job3|job descr3 |
 4|        1| 40|     3|      25|     24| 3|job3|job descr3 |

如您所见,有两个 id 字段,一个用于 recipe_details table,一个用于 jobs table。

问题是端点返回的javascript对象只有一个id属性不是主table,而是被最后一个覆盖了SQL 语句返回的 id 字段。

如何避免这种行为? 感谢您的帮助

发生这种情况是因为 node-pg 驱动程序的行为方式。当将多个列连接到行时,具有相同列名的连接列总是会覆盖 select 结果中较早的列。

您可以通过明确告知结果行的哪些列 select 来解决此问题。

赞:

knex("recipe_details")
    .select("recipe_details.*", "jobs.code", "jobs.description")
    .innerJoin("jobs", "jobs.id", recipe_details.id_job")
    .where("id_recipe", recipeId)