Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Bookshelf.js: how to define cross-relations?

Bookshelf.js: how to define cross-relations?

Problem

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/

Problem courtesy of: avasin

Solution

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
        }
    });
Solution courtesy of: Varun Oberoi

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Bookshelf.js: how to define cross-relations?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×