I've got two Bookshelf models in a many-to-many relationship and I'd like to have timestamps updated when I'm attaching or detaching some relations.
Here's my models:
var Video = Bookshelf.Model.extend({
tableName: 'video',
program: function(){
return this.belongsToMany(Bookshelf.model('Program'), 'programvideo', 'videoId', 'programId');
}
});
var Program = Bookshelf.Model.extend({
tableName: 'program',
videos: function(){
return this.belongsToMany(Bookshelf.model('Video'), 'programvideo', 'programId', 'videoId');
}
});
Everything works fine when I'm using
prgm.videos().attach(videos);
But is there any way to add timestamps to this relation? Do I need to define a pivot model in Bookshelf?
Thanks
Well, you could easily make a pivot model, create in migrations
timestamps
and enable timestamps in the model, and everything would work seamless!However, if you'd like to solve this without additional model, you have to define firstly
withPivot
in models, e.g.:Then, each time when you attach data, you have to call
updatePivot
, e.g.:I've commented the piece of code where you can filter a specific row in the junction table that gets updated (if left out, all corresponding rows get updated).
Hope this helps!