使用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');
});
};
发布于 2019-11-13 17:43:30
在更改表时,没有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?。
发布于 2021-05-26 12:11:31
老话题,但我找到了答案:
return knex.schema.table('the_table', table => {
table.tinyint('new_column').defaultTo('0').after('other_column')
})
这适用于Mysql数据库。
https://stackoverflow.com/questions/58828429
复制