Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually setting timestamp values in bookshelf.js

I have a table set up to have timestamps and bookshelf configured to use them. Normally everything happens as it should and bookshelf takes care of the timestamps, but I have a case where I want to specify them, but when I try to do that the values are ignored and the current date is used.

I've tried to simplify my use case down to the essentials:

var Author = Bookshelf.Model.extend({
  tableName: 'authors',
  hasTimestamps: ['created_at', 'updated_at'],

  bookAuthors: function(){
    return this.hasMany(require('.book_authors'));
  },

  associateBookWithAuthor(bookId,timestamp) {
    return self.related('bookAuthors').create({
      book_id: bookId,
      updated_at: timestamp, // ignored by bookshelf
      created_at: timestamp  // also ignored
    })
  }
}

I still want to keep the hasTimestamps configured for regular use cases. Is it possible to get Bookshelf to let me override the timestamps behavior?

like image 499
Gangstead Avatar asked Jul 25 '15 07:07

Gangstead


2 Answers

After looking at the Bookshelf source created_at and updated_at are set on create/insert as necessary and never read from the model you pass in: https://github.com/tgriesser/bookshelf/blob/c83ada77d5c670a773c0b47c604b452cd0e03e86/src/base/model.js#L413

This makes my goal impossible. Reflecting on that it seems like a good idea to not overload these columns and to create another column for the date I'm trying to store.

like image 85
Gangstead Avatar answered Sep 29 '22 12:09

Gangstead


Just updating right answer for new visitors to this question. The latest is bookshelf allows overriding timestamp values.

See official documentation and example here

https://bookshelfjs.org/api.html#Model-instance-hasTimestamps

myModel.save({created_at: new Date(2015, 5, 2)}).then(function(updatedModel) {
  // {
  //   name: 'blah',
  //   created_at: 'Tue Jun 02 2015 00:00:00 GMT+0100 (WEST)',
  //   updated_at: 'Sun Mar 25 2018 15:07:11 GMT+0100 (WEST)'
  // }
})
like image 28
Subramanyam S Avatar answered Sep 29 '22 13:09

Subramanyam S