【问题标题】:Knex migration timestamp not timestampingKnex 迁移时间戳没有时间戳
【发布时间】:2019-06-17 08:09:17
【问题描述】:
exports.up = async function(knex) {
  knex.schema.alterTable('posts', (t) => {
    t.timestamps(true, true)
  })
}

exports.down = async function(knex) {
  knex.schema.alterTable('posts', (t) => {
    t.dropTimestamps()
  })
}

根据文档,这将创建一个 created_atupdated_at 列。

但事实并非如此。

如何使用 Knex 创建这些列。

【问题讨论】:

  • 你是怎么执行的?

标签: knex.js


【解决方案1】:

您没有执行架构构建器。添加 await 或从迁移处理程序返回您的架构构建器。

exports.up = async function(knex) {
  return knex.schema.alterTable('posts', (t) => {
    t.timestamps(true, true)
  })
}

exports.down = async function(knex) {
  return knex.schema.alterTable('posts', (t) => {
    t.dropTimestamps()
  })
}

在@valem 的评论后编辑

如果不使用 async / await ,上面的代码几乎等同于:

exports.up = function(knex) {
  return Promise.resolve(knex.schema.alterTable('posts', (t) => {
    t.timestamps(true, true);
  }));
}

exports.down = function(knex) {
  return Promise.resolve(knex.schema.alterTable('posts', (t) => {
    t.dropTimestamps();
  }));
}

【讨论】:

  • 您忘记了 await 关键字。此外,这些不需要是异步函数。他们应该要么返回一个承诺,要么使用 async/await。
  • @valem 不,我没有。它们不需要异步,但它们应该是(我从 2015 年左右开始担任 knex 维护者)。将它们设置为异步函数会使它们隐含地始终返回 Promise。因此,async 关键字会导致返回的架构构建器(即 thenable)自动解析为 Promise。这确实是在 Node 的 async / await 时代编写迁移的首选方式。
  • 哦,我一直在做function(knex) { return knex.schema ... }。这是不正确的还是 knex 方法是一个承诺?
  • Knex.schema 是可以的。 Thenables 也可能有用,我记不太清了。
【解决方案2】:

试试这个(对我有用)

t.dropColumn('created_at');
t.dropColumn('updated_at');

而不是 t.dropTimestamps();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 2017-01-18
    • 2021-05-08
    • 2018-02-19
    • 2015-08-13
    • 2017-04-25
    相关资源
    最近更新 更多