【问题标题】:Set timestamps on a pivot model with Bookshelf.js使用 Bookshelf.js 在数据透视模型上设置时间戳
【发布时间】:2015-06-17 09:37:27
【问题描述】:

我有两个处于多对多关系的 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 中定义一个枢轴模型吗?

谢谢

【问题讨论】:

    标签: node.js orm bookshelf.js knex.js


    【解决方案1】:

    好吧,您可以轻松地创建一个枢轴模型,在迁移中创建 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);
                    });
                });
    
            });
    
        });
    });
    

    我已经注释了一段代码,您可以在其中过滤连接表中更新的特定行(如果省略,则所有相应的行都会更新)。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      • 2015-11-29
      相关资源
      最近更新 更多