How to build bookshelf.js relationships once the model defined?

bookshelf.js, orm, relationship

Solution

With the way you're doing it, you'd need to do it manually. You should be using the inverse relation like this:

var Country =  Bookshelf.Model.extend({
    tableName: 'countries',
    addresses: function() {
       return this.hasMany(Address);
    }
});

var Address =  Bookshelf.Model.extend({
    tableName: 'addresses',
    country: function() {
        return this.belongsTo(Country,'country_id');
    },
});

Then you should be able to do:

new Country({name: Italy}).fetch().then(function(italy) {

   // also could be italy.related('addresses'), that would add
   // the addresses collection to the "italy" model's "relations" hash
   return italy.addresses().create({...});

}).then(function(address) {

   // ... saved to the db with the correct address

});

Problem

I defined a Bookshelf model as ``` var Country = Bookshelf.Model.extend({ tableName: 'countries', }); var Address = Bookshelf.Model.extend({ tableName: 'addresses', country: function() { return this.belongsTo(Country,'country_id'); }, }); ``` Now I can fetch one of my models from the database ``` new Country({name:"Italy"}).fetch() .then(function(country){ ``` And create and Address ``` new Address({...}).save().then(function(address){ ``` But I can't find, in the documentation, what method would help me to build the 'belongsTo' relationship. without manually setting the country_id attribute to the right one. The only thing I see to build a relationship is the collection.create(object) method (http://bookshelfjs.org/#Collection-create) that is described as a convenience to create a model from an object,saving it, and adding it to the collection; I wouldn't know how to do the last part either. Anyway, collection.create seems not to be available for model.related('collectionName') when collectionName refers to hasOne or belongsTo relationships since they do not reprensent collections.

Original source