Bookshelf.js或Knex.js中2个表的外连接

use*_*531 5 javascript node.js bookshelf.js knex.js

我是Bookshelf.js和knex的新手.我需要在Bookshelf/knex中编写与此相当的查询

SELECT Inv.*, Comp.* 
FROM  Inv,   Comp
WHERE Inv.uId =2 AND Comp.cId = Inv.cId;
Run Code Online (Sandbox Code Playgroud)

Inv Table有:

Id     |  primary key, integer  not null
col1   | string data
cId    | integer, foreign key references C table
uId    | integer  foreign key reference U table      

Comp Table有:

cId     |  primary key, integer  not null 
col3    | string data

use*_*643 7

使用knex查询构建器.假设Invs是模型Inv的集合,它可能看起来像:

Invs.forge().query(function(qb) {
  qb.join('Comp', 'Comp.cId', '=', 'Inv.cId');
  qb.where('Inv.uId', 2);
}).fetch({withRelated: 'comps'}).then(...)
Run Code Online (Sandbox Code Playgroud)

comps是Inv模型中定义的关系.您也可以完全跳过书架,直接通过bookshelf.knex使用knex来形成您需要的确切查询:

bookshelf.knex('Inv')
  .join('Comp', 'Comp.cId', '=', 'Inv.cId')
  .where('Inv.id', 2)
  .select()
  .then(...)
Run Code Online (Sandbox Code Playgroud)

  • 我需要类似的复杂查询,看起来knex是不可避免的.我不知道为什么要将Bookshelf.js用作ORM呢?当使用纯粹的knex查询时,关联模型(一对一,一对等)等ORM功能似乎变得毫无用处. (7认同)