2017-05-21 11 views
0

Knex.jsの移行を使用してデータベース内の既存のデータを変更することはできますか?Knex.js移行で既存のデータを移動/コピーする

たとえば、データベースに既存のカラム 'name'があり、それを2つのカラム 'first_name'と 'last_name'に分割したい場合は、移行でこれを行うことは可能ですか?

答えて

3

うんこのような何かを行う必要があります

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() {}; 
関連する問題