Knex.js 迁移 move/copy 现有数据
Knex.js Migrations move/copy existing data
是否可以使用 Knex.js 迁移修改数据库中的现有数据?
例如,如果我的数据库中有一个现有的列 'name',我想将它分成两列 'first_name' 和 'last_name',是否可以这样做与迁移?
是的
应该这样做:
exports.up = function (knex) {
return knex.schema.table('your_table', (table) => {
table.string('first_name');
table.string('last_name');
}).then(() => {
return knex('your_table').update({
// this requires that each name are in form 'fistname lastname'
// if you need to do more complex transformation regexp_split_to_array migth help
first_name: knex.raw(`split_part(??, ' ', 1)`, ['name']),
last_name: knex.raw(`split_part(??, ' ', 2)`, ['name'])
});
}).then(function () {
// drop original column, but I would suggest leaving it in
// to be able to verify values in new columns
});
};
exports.down = function () {};
是否可以使用 Knex.js 迁移修改数据库中的现有数据?
例如,如果我的数据库中有一个现有的列 'name',我想将它分成两列 'first_name' 和 'last_name',是否可以这样做与迁移?
是的
应该这样做:
exports.up = function (knex) {
return knex.schema.table('your_table', (table) => {
table.string('first_name');
table.string('last_name');
}).then(() => {
return knex('your_table').update({
// this requires that each name are in form 'fistname lastname'
// if you need to do more complex transformation regexp_split_to_array migth help
first_name: knex.raw(`split_part(??, ' ', 1)`, ['name']),
last_name: knex.raw(`split_part(??, ' ', 2)`, ['name'])
});
}).then(function () {
// drop original column, but I would suggest leaving it in
// to be able to verify values in new columns
});
};
exports.down = function () {};