【问题标题】:Knex.js Migrations move/copy existing dataKnex.js 迁移移动/复制现有数据
【发布时间】:2017-05-23 14:51:51
【问题描述】:

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

例如,如果我的数据库中有一个现有的列“名称”,并且我想将它分成两列“名字”和“姓氏”,是否可以通过迁移来做到这一点?

【问题讨论】:

    标签: knex.js


    【解决方案1】:

    是的

    应该这样做:

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

    【讨论】:

      猜你喜欢
      • 2017-12-21
      • 1970-01-01
      • 1970-01-01
      • 2014-05-02
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 2017-11-22
      • 1970-01-01
      相关资源
      最近更新 更多