使用Bookshelf.js在透视模型上设置时间戳

我有两个Bookshelf模型在多对多的关系,我想附加或分离一些关系时更新时间戳。

这是我的模型:

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'); } }); 

一切正常,当我使用

 prgm.videos().attach(videos); 

但是有什么办法给这个关系添加时间戳吗? 我是否需要在Bookshelf中定义枢纽模型?

谢谢

那么,你可以很容易地创build一个数据透视模型,创build迁移timestamps并在模型中启用时间戳,一切都将无缝工作!

但是,如果您想在没有附加模型的情况下解决此问题,则必须首先在模型中使用withPivot定义,例如:

 var Stations = bookshelf.Model.extend({ tableName: 'stations', stationsRoutes: function() { return this.belongsToMany(Routes, 'stations_routes').withPivot('time'); } }); var Routes = bookshelf.Model.extend({ tableName: 'routes', stationsRoutes: function() { return this.belongsToMany(Stations, 'stations_routes').withPivot('time'); } }); 

然后,每次附加数据时,都必须调用updatePivot ,例如:

 router.get('/updatePivot/:id', function(req, res) { new Routes({ 'id': req.params.id }).fetch({ withRelated: ['stationsRoutes'] }).then(function(result) { result.stationsRoutes().attach({ station_id: 3 }).then(function() { result.stationsRoutes().updatePivot({ 'time': '09:09' }/*, { query: function(qb) { qb.where({ 'id': 8 }); } }*/).then(function() { result.load('stationsRoutes').then(function(result_reloaded){ res.json(result_reloaded); }); }); }); }); }); 

我已经评论了一段代码,您可以在结合表中更新特定行(如果省略,所有对应的行都会更新)。

希望这可以帮助!