avasin
avasin

Reputation: 9726

Bookshelf.js: how to define cross-relations?

How can i define hasMany Space -> Accounts relation?

var Space = Bookshelf.Model.extend({
    tableName : 'spaces',
    // Account variable does not exist :/
});

var Account = Bookshelf.Model.extend({
    tableName : 'accounts',
    spaceId   : function() {
        return this.belongsTo(Space);
    },
});

What is the correct way to define this?

P.S. There is no tag for bookshelf js library: http://bookshelfjs.org/

Upvotes: 1

Views: 3675

Answers (1)

Varun Oberoi
Varun Oberoi

Reputation: 692

According to Docs, this should work:

    var Account = Bookshelf.Model.extend({
        tableName : 'accounts'
    });

    var Space = Bookshelf.Model.extend({
        tableName : 'spaces',
        accounts  : function() {
            return this.hasMany(Account, 'spaceId'); // spaceId is foreign key for Account table
        }
    });

Upvotes: 8

Related Questions