【问题标题】:Migration: add a column after a specific column迁移:在特定列之后添加一列
【发布时间】:2020-03-08 17:43:16
【问题描述】:

这用 SQL 很容易做到,但我需要编写一个我不熟悉的 Knex 迁移脚本。下面在order 表的行尾添加order_id 列。我希望在id 之后添加order_id。我该怎么做?

const TABLE_NAME = 'order';
exports.up = function (knex) {
    return knex.schema.alterTable(TABLE_NAME, table => {
        table
            .specificType('order_id', 'char(10)')
            .unique()
            .notNullable();

    });
};

exports.down = function (knex) {
    return knex.schema.table(TABLE_NAME, function (t) {
        t.dropColumn('order_id');
    });
};

【问题讨论】:

    标签: migration knex.js


    【解决方案1】:

    没有确定更改表时的列顺序的 SQL。顺序是根据查询确定的,例如:

    knex
      .select('id', 'order_id')
      .from('order')
    

    产量

    id | order_id
    ===+=========
    1  | 2
    

    knex
      .select('order_id', 'id')
      .from('order')
    

    产量

    order_id | id
    =========+===
    2        | 1
    

    如果单个数据库引擎确实支持在创建表后更改列的顺序,那将是该引擎特有的,并且对于像 Knex 这样的 SQL 生成器来说不容易操作。请参阅How do I alter the position of a column in a PostgreSQL database table? 了解更多信息。

    【讨论】:

      【解决方案2】:

      老话题,但我找到了答案:

      return knex.schema.table('the_table', table => {    
          table.tinyint('new_column').defaultTo('0').after('other_column')
      })
      

      这适用于 Mysql 数据库。

      【讨论】:

        猜你喜欢
        • 2016-09-09
        • 2015-10-20
        • 1970-01-01
        • 2018-05-01
        • 2013-03-07
        • 2014-01-25
        • 2018-06-28
        • 1970-01-01
        • 2013-07-06
        相关资源
        最近更新 更多