首页 > 解决方案 > 如何使用 1 knex 脚本创建整个数据库的迁移?

问题描述

在我的数据库中,我有大约 50 张桌子。每张桌子都有created_atupdated_at。当然,我可以创建 50 个迁移,但会有类似的。是否有机会创建knex可以对整个数据库进行 50 次迁移的脚本?

这是代码示例:

exports.up = function(knex, Promise) {
  return knex.schema.alterTable("balance", table => {
    table.timestamp("created_at").defaultTo(knex.fn.now()).alter()
    table
      .timestamp("updated_at")
      .defaultTo(knex.raw("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")).alter()
  })
};

exports.down = function(knex, Promise) {
  return knex.schema.alterTable("balance", table => {
    table.dateTime("created_at").defaultTo(null).alter()
    table.dateTime("updated_at").defaultTo(null).alter()
  })
};

Balance是表的名称,所以我必须创建大约 50 个迁移,只更改数据库的名称。是否可以仅使用 1 个 knex 脚本使一切变得更容易?

感谢您的回答!

标签: javascriptknex.js

解决方案


就像这样:

const showList = await knex.raw(
`SELECT table_name FROM information_schema.tables WHERE table_schema = 'your_db';`)

for (const item of showList[0]) {
  await knex.schema.alterTable(`${item.table_name}`, table => {
    table.timestamp("created_at").defaultTo(knex.fn.now()).alter()
    table
      .timestamp("updated_at")
      .defaultTo(knex.raw("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")).alter()
  })
}

推荐阅读