如何在一个查询中从 3 Bookshelf.js 个模型中获取数据

How can I get data from 3 Bookshelf.js models in one query

我有 3 个表:UserUserDrinkVenueDrink

这是我的示例数据

User
id | name | gender |
--------------------
1  | John | male   |
2  | Jane | female |

UserDrink
id | count | user_id | venue_drink_id
1  | 3     | 1       | 1
2  | 5     | 1       | 2
3  | 2     | 2       | 2

VenueDrink
id | name | price
1  | Beer | 50
2  | Wine | 100

当我查询单个 User 时,如何使用 BookshelfJs 获取以下 return?

{
  "id":1,
  "name":"John",
  "gender":"male",
  "user_drinks":[
    {
      "id":1,
      "count":3,
      "user_id":1,
      "venue_drink":{
        "id":1,
        "name":"Beer",
        "price":50
      }
    },
    {
      "id":2,
      "count":5,
      "user_id":1,
      "venue_drink":{
        "id":2,
        "name":"Wine",
        "price":100
      }
    }
  ]
}

我尝试了几次,但我是 BookshelfJs 的新手,不幸的是,我只能使用 withRelatedhasMany 关系达到 UserDrink 级别。 我只能输出以下内容:

{
  "id":1,
  "name":"John",
  "gender":"male",
  "user_drinks":[
    {
      "id":1,
      "count":3,
      "user_id":1,
      "venue_drink_id":1
    },
    {
      "id":2,
      "count":5,
      "user_id":1,
      "venue_drink_id":2
    }
  ]
}

我需要使用 venue_drink_id 输出 venue_drink 的详细信息。 提前致谢。

您可以按如下方式获取想要的结果

var user = db.Model.extend({
   tableName: 'users',
   hasTimestamps: false,
   drinks: function() {
     return this.hasMany(UserDrink, 'user_id');
   }
});
var UserDrink = db.Model.extend({
   tableName: 'UserDrink',
   hasTimestamps: false,

   venueDrink: function() {
     return this.belongsTo(VenueDrink, 'venue_drink_id');
   }
   userRelated : function() {
     return this.belongsTo(user,'user_id');
   }
});
var VenueDrink = db.Model.extend({
   tableName: 'VenueDrink',
   hasTimestamps: false
});
user.where({
   id: 1
}).fetchAll({
   withRelated: ['drinks.venueDrink', 'drinks.userRelated']
}).then(function(data) {
   data = data.toJSON();
   res.send(data);
});