是否可以使用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 () {};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1242 次 |
| 最近记录: |