2017-02-04 68 views
1

我想从我的m-n关系型mySql表中使用Bookshelf.js获取属性。Bookshelf.js获取数据透视表属性

我有一个表的用户:ID,名称 和比赛:ID,将 和数据透视表: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" 
     }, ... 
} 

任何人知道如何使用书架做到这一点?

回答

0

您可以使用​​方法。

使用这样的:

users: function() { 
    return this.belongsToMany(User).withPivot(['teamname']); 
} 

在你的回报,你会得到一个名为_pivot_teamname场。只需重新命名它们即可。 文档:http://bookshelfjs.org/#Collection-instance-withPivot

只要我知道,没有办法使用自定义名称获取数据透视表字段。