Knex.js迁移移动/复制现有数据

时间:2017-05-21 19:24:36

标签: knex.js

是否可以使用Knex.js迁移修改数据库中的现有数据?

例如,如果我的数据库中有一个现有列'name',并且我想将其拆分为两列'first_name'和'last_name',是否可以通过迁移执行此操作?

1 个答案:

答案 0 :(得分:5)

是的

这样的事情应该做:

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 () {};