运行 knex 迁移内部更新
Run update inside knex migration
我想向 table 添加一列,然后执行一些工作来填充该列作为迁移的一部分。填充该列需要在代码中进行一些操作。
考虑两个 table:
- 用户
[ user_id, first_name, last_name ]
和
- 订单
[ order_id, user_id, other_field_1, other_field_2 ]
。
和函数
var getNickName = function(user_row) {
//do a bunch of javascripty stuff here
//based on user_row.first_name and user_row.last_name.
//i.e., stuff not possible in SQL
return 'nickname';
}
我想要一个将 user_nick_name
字段添加到订单 table 的 knex 迁移。然后使用 getNickName()
.
的输出更新新列
我需要这个 在交易中。
我知道我需要将列添加到订单,然后 select 所有订单,遍历执行的订单:
将用户行传递到 getNickName
,
然后使用它来调用用户 table 设置值的更新。
当涉及交易时,我似乎无法理解所有这些的 knex 语法。
export function up(knex, Promise) {
return knex.select()
.from('Users')
.then((users) => {
const nickNames = users.map((user) => {
return { userId: user.user_id, nickName: getNickName(row) };
});
return knex.transaction((trx) => {
return knex.schema.table('Orders', (table) => table.string('user_nick_name').transacting(trx))
.then(() => {
return Promise.all(
nickNames.map((row) => {
return knex('Orders')
.update({ user_nick_name: row.nickName })
.where('user_id', row.userId)
.transacting(trx);
});
);
})
.then(trx.commit)
.catch(trx.rollback);
});
});
}
export function down(knex) {
return knex.schema.table('Orders', (table) => table.dropColumn('user_nick_name'));
}
我想向 table 添加一列,然后执行一些工作来填充该列作为迁移的一部分。填充该列需要在代码中进行一些操作。
考虑两个 table:
- 用户
[ user_id, first_name, last_name ]
和 - 订单
[ order_id, user_id, other_field_1, other_field_2 ]
。
和函数
var getNickName = function(user_row) {
//do a bunch of javascripty stuff here
//based on user_row.first_name and user_row.last_name.
//i.e., stuff not possible in SQL
return 'nickname';
}
我想要一个将 user_nick_name
字段添加到订单 table 的 knex 迁移。然后使用 getNickName()
.
我需要这个 在交易中。
我知道我需要将列添加到订单,然后 select 所有订单,遍历执行的订单:
将用户行传递到 getNickName
,
然后使用它来调用用户 table 设置值的更新。
当涉及交易时,我似乎无法理解所有这些的 knex 语法。
export function up(knex, Promise) {
return knex.select()
.from('Users')
.then((users) => {
const nickNames = users.map((user) => {
return { userId: user.user_id, nickName: getNickName(row) };
});
return knex.transaction((trx) => {
return knex.schema.table('Orders', (table) => table.string('user_nick_name').transacting(trx))
.then(() => {
return Promise.all(
nickNames.map((row) => {
return knex('Orders')
.update({ user_nick_name: row.nickName })
.where('user_id', row.userId)
.transacting(trx);
});
);
})
.then(trx.commit)
.catch(trx.rollback);
});
});
}
export function down(knex) {
return knex.schema.table('Orders', (table) => table.dropColumn('user_nick_name'));
}