在bookshelf.js中手动设置时间戳值

问题描述 投票:5回答:2

我有一个表设置有时间戳和书架配置使用它们。通常一切都按照应有的方式发生,书架会处理时间戳,但我有一个案例需要指定它们,但是当我尝试这样做时,会忽略这些值并使用当前日期。

我试图将我的用例简化为基本要素:

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

我仍然希望保持hasTimestamps配置为常规用例。是否有可能让Bookshelf让我覆盖时间戳行为?

javascript node.js bookshelf.js knex.js
2个回答
1
投票

只是为这个问题的新访问者更新正确的答案。最新的书架允许覆盖时间戳值。

请参阅此处的官方文档和示例

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

5
投票

查看Bookshelf源后,create_at和updated_at会根据需要在create / insert上设置,并且永远不会从您传入的模型中读取:https://github.com/tgriesser/bookshelf/blob/c83ada77d5c670a773c0b47c604b452cd0e03e86/src/base/model.js#L413

这使我的目标变得不可能。反思这似乎是一个好主意,不要重载这些列,并为我试图存储的日期创建另一列。

© www.soinside.com 2019 - 2024. All rights reserved.