使用库knex.js连接三个表

时间:2018-11-19 15:38:08

标签: node.js express knex.js

我正在使用knex.js

假设我们有三个表:- table1-ID,名称,地址 table2--id,city,sate,table1_id为fk table3--id,housenumber,table1_id as fk

我想使用节点的knex.js libraray加入这三个表并表达 这样我想得到这样的输出json。

{  “ id”:1,  “ name”:“ abc”,  “地址:” xyz”,  “ table2”:{“ id”:1,“ city”:“ ttt”,“ state”:“ www”} //我要检查table1.id == table2.table1_id然后放入表详细信息  “ table3”:[] //如果在table1.id === table3.table1.id之间找不到任何关系,则将其保留为数组 }

1 个答案:

答案 0 :(得分:0)

tl; dr knex对于您尝试做的事情来说太底层了,您应该使用ORM来完成此类任务

但是,您可以通过大量的手工工作来做到这一点。

首先,您必须使用适当的联接进行查询,并为表的每一列创建带表前缀的别名,以便能够以所有数据都在平面数组中的格式获取结果数据,例如:

knex('table1' as t1)
  .join('table2 as t2', 't2.t1_id', 't1.id')
  .select(
    't1.id as t1_id', 
    't1.other_column as t1_other_column', 
    't2.id as t2_id', <more columns you want to extract>)

结果类似

[ { t1_id: 1, t1_other_column: 'foo', t2_id: 4}, ... more rows with flat data... }]

然后,您需要编写JavaScript代码以将平面数据重组为嵌套对象。

但是您不应该手动执行此类工作。所有基于knex的ORM都已经实现了通用的解决方案,可以轻松地编写这种查询。