2017-02-04 109 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

只要我知道,沒有辦法使用自定義名稱獲取數據透視表字段。

相關問題