我想为以下查询创建迁移文件
`insert into table1(column1)
select o.name from original_table as o`
`update original_table as o
set new_column = (select t1.id from table1 as t1
where t.column1 = o.old_column)`
到目前为止,我想到了这个。第一部分有效,但是我对第二部分感到困惑
`exports.up = function (knex, Promise) {
return Promise.resolve()
.then(() => knex('original_table').select('old_column'))
.then((rows) => knex('table1').insert(rows))
.then(() => knex('table1 as t').select(['t.column1',
'column2']).join('original_table
as o', 'o.old_column', 't.column2'))
.then((rows) => knex('original_tableas
o').whereIn('original_table.old_column', rows.column2).update('column2',
rows.column1))
};
exports.down = function (knex) {
return Promise.resolve()
.then(() => console.log("Deletes updated records"));
};`
谢谢。
答案 0 :(得分:0)
使用knex进行第一次查询实际上非常不便,但是knex.raw
可以做很多事情。以下是我想到的最讨厌的方式:
exports.up = async (knex) => {
// insert into table1(column1) select o.name from original_table as o
await knex.raw('insert into ?? (??) ??', ['table1', 'column1', knex('original_table').select('name')]);
// update original_table as o set
// new_column = (
// select t1.id from table1 as t1 where t1.column = o.old_column
// )
await knex('original_table as o').update({
new_column: knex('table1 as t1').select('id').where('t1.column', 'o.old_column')
});
}