【问题标题】:How would I perform a multi-join query in Bookshelf.js?如何在 Bookshelf.js 中执行多连接查询?
【发布时间】:2015-12-09 05:32:30
【问题描述】:

基本上,我有两个表:User 和 user_connections

User:

id | email

1 | name@domain.com

2 | name1@domain.com

user_connections:

user_id | key

1 | test1

1 | test2

2 | test3

基本上,我需要构建一个查询,在给定电子邮件的情况下,提取与该电子邮件 ID 关联的连接列表。

我已经定义了User 并指向User 表。我将如何获得所需的结果?


编辑:这是想要的结果:

如果我 GET 的 id 为 1,那么我应该得到以下返回(以 JSON 格式):

{
  {
    user_id: 1,
    key: test1
  },
  {
    user_id: 2,
    key: test2
  }
}

【问题讨论】:

  • 显示你想要的结果
  • 我已经编辑了问题以表明这一点。
  • 在查询方法中使用join和where

标签: javascript sql bookshelf.js


【解决方案1】:

在传递给fetch 的哈希中使用withRelated。它标识了您必须在书架模型中定义的列名数组。

User
    .forge()
    .where({email: "me@me.com"})
    .fetch({
        withRelated: ["user_connections"] //or however you have defined it in your model defintion
    })
    .then(function(collection) {
        collection.relations// {user_connections: [ {}, {}, ...]}
    });

【讨论】:

    【解决方案2】:
    User.query().join('user_connections','User.id','=','user_connections.user_id').where('user.email','=','abc').select('user_connections.key','user_connections.user_id').then(function(collection){
        res.json(collection);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      • 1970-01-01
      • 2020-02-21
      相关资源
      最近更新 更多