简体   繁体   English

我将如何在 Bookshelf.js 中执行多连接查询?

[英]How would I perform a multi-join query in Bookshelf.js?

Basically, I have two tables: User and user_connections基本上,我有两个表: User 和 user_connections

User : User

id | email

1 | name@domain.com

2 | name1@domain.com

user_connections : user_connections

user_id | key

1 | test1

1 | test2

2 | test3

Basically, I need to construct a query that, given the email, pulls a list of connections associated with that email's id.基本上,我需要构建一个查询,在给定电子邮件的情况下,提取与该电子邮件 ID 关联的连接列表。

I already have User defined and pointing to the User table.我已经有User定义并指向User表。 How would I get the required results?我将如何获得所需的结果?


EDIT: Here is the desired result:编辑:这是所需的结果:

If I GET with an id of 1 , then I should get the following returned (in JSON):如果我GET的 id 为1 ,那么我应该得到以下返回(在 JSON 中):

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

Use withRelated in the hash you pass to fetch .在传递给fetch的哈希中使用withRelated It identifies an array of column names that you must have defined in your bookshelf model.它标识您必须在书架模型中定义的列名数组。

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: [ {}, {}, ...]}
    });
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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM