Set timestamps on a pivot model with Bookshelf.js

1k views Asked by At

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

1

There are 1 answers

0
uglycode On BEST ANSWER

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.:

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

Then, each time when you attach data, you have to call updatePivot, e.g.:

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

        });

    });
});

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!