[英]How can I get data from 3 Bookshelf.js models in one query
I have 3 tables: User
, UserDrink
, and VenueDrink
我有3个表: User
, UserDrink
和VenueDrink
Here are my sample data 这是我的样本数据
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
How can I get the following return using BookshelfJs
when I query a single User
? 当查询单个User
时,如何使用BookshelfJs
获得以下收益?
{
"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
}
}
]
}
I tried several attempts but I'm new to BookshelfJs
and unfortunately, I can only go up to UserDrink
level using withRelated
and hasMany
relationship. 我尝试了几次尝试,但是我是BookshelfJs
新手,但是不幸的是,我只能使用withRelated
和hasMany
关系提升到UserDrink
级别。 I can only output the following: 我只能输出以下内容:
{
"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
}
]
}
I need to output the details of the venue_drink
using the venue_drink_id
. 我需要使用venue_drink_id
输出venue_drink
的详细信息。 Thanks in advance. 提前致谢。
You can fetch the desired result as follows 您可以按以下方式获取所需结果
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.