Knex迁移:将新列的值添加到预先存在的记录中

问题描述 投票:0回答:1

使用knex我想向现有表中添加2个其他列。为了预先存在记录,我想基于计算添加一个值。我已经复制了另一个迁移文件,并尝试将其调整为适合自己的情况,但是没有运气。以下是我的迁移文件。它在第二行失败:Cannot read property 'resolve' of undefined。我该如何解决?

exports.up = function (knex, Promise) {
  return Promise.resolve()
    .then(function(){
      return knex.schema.table('transactions', (table) => {
        table.decimal('plan_price', 10, 2);
        table.decimal('discount', 10, 2).defaultTo(0);
      });

    }).then(function(return_value){
      knex.select(['id']).from('transactions').then((transactions) => {
        transactions.forEach(async function(trans){
            ... cut to shorten question...
        })
      })

      return return_value;
    })
};

更新:我删除了Promise,现在下面有迁移代码。我仅回滚了最新的迁移。现在,在迁移时,将产生以下两个错误:

未处理的拒绝MigrationLocked:迁移表已被锁定

交易查询已经完成,请使用DEBUG = knex:tx来运行以获取更多信息

const Coupon = require('../../models/coupon');
const Plan = require('../../models/plan');

exports.up = function (knex) {
    return knex.schema.table('transactions', (table) => {
      table.decimal('plan_price', 10, 2);
      table.decimal('discount', 10, 2).defaultTo(0);
    })

    .then(function(return_value){
      knex.select().from('transactions')
      .then((transactions) => {
        transactions.forEach(async function(trans){
          let original_price;
          let total_coupon_discount = 0;

          const plan = await Plan.where({id: trans.plan_id}).fetch();
          if (plan) { original_price = plan.get("price") };

          if (trans.coupon_id) {
            const coupon = await Coupon.where({id: trans.coupon_id}).fetch();
            if (coupon) {
              const amount_ex_vat = trans.amount_ex_vat;
              const couponAmount = coupon.get("discount_amount");
              original_price = amount_ex_vat + couponAmount;
              total_coupon_discount = original_price - amount_ex_vat;
            }
          }

          knex('transactions')
          .where('id', '=', trans.id)
          .update({
            plan_price: original_price,
            discount: total_coupon_discount
          }).catch(function(error){
            console.log(error)
          }).then(function(){
            console.log('Added data to transaction record');
          })
        })
      })

      return return_value;
    })
};
mysql node.js database-migration knex.js
1个回答
0
投票

Knex不再采用第二个Promise参数,因为它转而使用了一段时间的本机Promise。因此,Promise在您的迁移中是undefined,因此绝对没有.resolve属性。

有人认为返回Promise.resolve().then绝对是个好主意,这很奇怪。您要执行的是模式修改,然后是数据修改。看起来像这样:

return knex.schema.table("transactions", t => {
  t.decimal('plan_price', 10, 2);
  // etc
})
  .then(() =>
    knex("transactions")
      .then(
        // Update values here
      );
  )
  .catch(console.error)
© www.soinside.com 2019 - 2024. All rights reserved.