我有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


查询单个BookshelfJs时如何使用User得到以下返回?

{
  "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还是陌生的,不幸的是,我只能使用UserDrinkwithRelated关系升至hasMany级别。
我只能输出以下内容:

{
  "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输出venue_drink_id的详细信息。
提前致谢。

最佳答案

您可以按以下方式获取所需结果

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);
});

09-07 22:49