Alex Hans
Alex Hans

Reputation: 538

Bookshelf.js get pivot table attributes

I am trying to get attributes from my m-n relational mySql table using Bookshelf.js.

I have a table users: id, name and tournaments: id, place and a pivot table: user_id, tournament_id, teamname

Those are my models:

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

Now when I do

Tournaments.forge().fetch({withRelated: ['users']})
.then(function (collection) {
    res.send(collection.toJSON());
})

I get

{
    "id": 1,
    "place": "Berlin",
    "users": [
        {
            "id": 1,
            "name": "Jim",
        },
        {
            "id": 2,
            "name": "Tom",
        }, ...
}

What I want:

{
    "id": 1,
    "place": "Berlin",
    "users": [
        {
            "id": 1,
            "name": "Jim",
            "teamname" : "Team A"
        },
        {
            "id": 2,
            "name": "Tom",
            "teamname" : "Team B"
        }, ...
}

Anyone knows how to do this using Bookshelf?

Upvotes: 2

Views: 1418

Answers (1)

Eric Ly
Eric Ly

Reputation: 2133

You may use .withPivot() method.

Use it like this :

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

In your return, you will get a field named _pivot_teamname. Just rename them to get it good. Documentation : http://bookshelfjs.org/#Collection-instance-withPivot

As long as I know, there is no way to fetch the pivot fields with a custom name.

Upvotes: 3

Related Questions