2017-02-04 7 views
1

Bookshelf.jsを使用して、m-nリレーショナルmySqlテーブルから属性を取得しようとしています。Bookshelf.jsがピボットテーブルの属性を取得する

私はテーブルのユーザーを持っている:ときに私今

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' 
}); 

:idは、名前 やトーナメント:これらは私のモデルですuser_idは、tournament_id、TEAMNAME

:idは、 とピボットテーブルを配置します私が手

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" 
     }, ... 
} 

は、誰もが本棚を使ってこれを行う方法を知っていますか?

答えて

0

​​メソッドを使用できます。

はこのようにそれを使用してください:あなたのリターンで

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

、あなたは_pivot_teamnameという名前のフィールドを取得します。それを良いものにするために名前を変更するだけです。 ドキュメント:http://bookshelfjs.org/#Collection-instance-withPivot

私が知っている限り、ピボットフィールドをカスタム名でフェッチする方法はありません。