【问题标题】:Manually setting timestamp values in bookshelf.js在 bookshelf.js 中手动设置时间戳值
【发布时间】:2015-07-25 07:23:05
【问题描述】:

我有一个表设置有时间戳和书架配置为使用它们。通常一切都会按原样发生,而 bookshelf 会处理时间戳,但我有一个案例我想指定它们,但是当我尝试这样做时,这些值将被忽略并使用当前日期。

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

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      在此处查看官方文档和示例

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-24
        • 1970-01-01
        • 2018-05-24
        • 1970-01-01
        • 1970-01-01
        • 2012-12-06
        • 1970-01-01
        相关资源
        最近更新 更多