Nor*_*cUs 2 orm node.js bookshelf.js knex.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');
}
});
Run Code Online (Sandbox Code Playgroud)
当我使用时一切正常
prgm.videos().attach(videos);
Run Code Online (Sandbox Code Playgroud)
但是有什么办法可以为这种关系添加时间戳吗?我需要在 Bookshelf 中定义枢轴模型吗?
谢谢
好吧,您可以轻松地创建一个数据透视模型,在迁移中创建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');
}
});
Run Code Online (Sandbox Code Playgroud)
然后,每次附加数据时,您都必须调用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);
});
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
我已经注释了一段代码,您可以在其中过滤连接表中更新的特定行(如果遗漏,所有相应的行都会更新)。
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
1092 次 |
| 最近记录: |