Skip to content

Instantly share code, notes, and snippets.

@stefanhenze
Created March 27, 2014 23:10
Show Gist options
  • Save stefanhenze/9821183 to your computer and use it in GitHub Desktop.
Save stefanhenze/9821183 to your computer and use it in GitHub Desktop.
Bookshelf.js relations
var Parent = Bookshelf.Model.extend({
tableName: 'parent',
child: function() {
return this.hasOne(Child);
}
});
var Child = Bookshelf.Model.extend({
tableName: 'child',
//this has an attribute parent_id
parent: function() {
return this.belongsTo(Parent);
}
});
var parent, child;
Parent.forge({name: "Parent"}).save()
.then(function (_parent) {
parent = _parent;
return Child.forge({name: "Child"}).save();
})
.then(function (_child) {
child = _child;
child.related('parent').set(parent);
return child.save();
})
.then(function(saved) {
res.send(saved);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment