Reputation: 521
I am trying to add a new column to existing tableName
table which has a column anotherColumn
.
exports.up = function (knex, Promise) {
return knex.schema.table('tableName', table => {
table.string('newColumn').defaultTo(table.anotherColumn);
});
};
How should I get the value of the existing column into this new column?
Upvotes: 2
Views: 2897
Reputation: 7654
The short answer is, you can't: the defaultTo
value can't come from another column. However, if you're just trying to have the default take place at the time of migration you could do this:
exports.up = knex =>
knex.schema.table('tableName', t => {
t.string('newColumn')
})
.then(() => knex('tableName').update('newColumn', knex.ref('anotherColumn'));
It should hopefully be obvious that this will not update new rows being inserted following the migration: for that you'd need a trigger, or to ensure that you covered it in your insert code.
Upvotes: 3