我正在尝试使用Bookshelf.js从我的m-n关系mySql表中获取属性。
我有一个表用户:id,name 和锦标赛:身份,地点 和数据透视表:user_id,tournament_id,teamname
这些是我的模特:
var User = Bookshelf.Model.extend({
tableName: 'users',
tournaments: function () {
return this.belongsToMany(Tournament);
}
});
var Users = Bookshelf.Collection.extend({
model: User
});
var Tournament = Bookshelf.Model.extend({
tableName: 'tournaments',
users: function () {
return this.belongsToMany(User);
}
});
var Tournaments = Bookshelf.Collection.extend({
model: Tournament
});
var Tournaments_Users = Bookshelf.Model.extend({
tableName: 'tournaments_users'
});
现在我做的时候
Tournaments.forge().fetch({withRelated: ['users']})
.then(function (collection) {
res.send(collection.toJSON());
})
我得到了
{
"id": 1,
"place": "Berlin",
"users": [
{
"id": 1,
"name": "Jim",
},
{
"id": 2,
"name": "Tom",
}, ...
}
我想要的是什么:
{
"id": 1,
"place": "Berlin",
"users": [
{
"id": 1,
"name": "Jim",
"teamname" : "Team A"
},
{
"id": 2,
"name": "Tom",
"teamname" : "Team B"
}, ...
}
任何人都知道如何使用Bookshelf做到这一点?
答案 0 :(得分:1)
您可以使用.withPivot()
方法。
像这样使用:
users: function () {
return this.belongsToMany(User).withPivot(['teamname']);
}
在您的回程中,您将获得一个名为_pivot_teamname
的字段。只需将它们重命名即可。
文档:http://bookshelfjs.org/#Collection-instance-withPivot
只要我知道,就无法使用自定义名称获取数据透视字段。