Mysql Bookshelf.js获取数据透视表属性
我正在尝试使用Bookshelf.js从我的m-n关系mySql表中获取属性 我有一个表用户:id,name 和比赛:身份证,地点 和数据透视表:用户id、锦标赛id、团队名称 这些是我的模型:Mysql Bookshelf.js获取数据透视表属性,mysql,sql,orm,knex.js,bookshelf.js,Mysql,Sql,Orm,Knex.js,Bookshelf.js,我正在尝试使用Bookshelf.js从我的m-n关系mySql表中获取属性 我有一个表用户:id,name 和比赛:身份证,地点 和数据透视表:用户id、锦标赛id、团队名称 这些是我的模型: var User = Bookshelf.Model.extend({ tableName: 'users', tournaments: function () { return this.belongsToMany(Tournament); } }); var
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",
"teamname" : "Team A"
},
{
"id": 2,
"name": "Tom",
"teamname" : "Team B"
}, ...
}
任何人都知道如何使用Bookshelf进行此操作?您可以使用
.withPivot()
方法
像这样使用它:
users: function () {
return this.belongsToMany(User).withPivot(['teamname']);
}
在您的返回中,您将得到一个名为\u pivot\u teamname
的字段。只要重新命名它们就可以了。
文件:
据我所知,没有办法获取具有自定义名称的pivot字段
users: function () {
return this.belongsToMany(User).withPivot(['teamname']);
}