如何 运行 sequelize hooks 中的另一个模型查询?

How to run another model queries inside the sequelize hooks?

下面是我在 sequelize 中定义的 PurchaseOrder 模型。每当 PurchaseOrder 有更新时,我想更新供应商模型。我想到了使用钩子来实现这一点。但是我无法访问该模型中的另一个模型。我尝试导入和所有东西,但没有运气。这是使用挂钩的正确方法还是我应该使用什么来实现相同的目的?非常感谢任何帮助或指导!

module.exports = (sequelize, Sequelize) => {
  const PurchaseOrder = sequelize.define("purchaseOrder", {
    totalAmount: {
      type: Sequelize.INTEGER
    },
    paid: {
      type: Sequelize.BOOLEAN
    },
    paymentMode: {
      type: Sequelize.ENUM('CASH', 'CHEQUE', 'BANK', 'CARD', 'NA')
    }
  }, {
    freezeTableName: true,
    hooks: {
      beforeUpdate: (order, options) => {
        // here I want to update the another model(Supplier).
        // But I couldn't able to access another model inside the hook
        Supplier.increment('balance'{
           where: { id: order.supplierId }
        });
      }
    }
  });

  return PurchaseOrder;
};

您可以尝试sequelize['Supplier'],因为所有模型都应该已经在 Sequelize 实例中注册。

尽管如此,我认为通过此类挂钩中的其他模型在数据库中进行修改不是一个好主意,因为在这种情况下,您应该考虑到所有操作都应在同一事务中完成,即应作为如果某些修改失败,避免数据库中数据状态不一致的原子操作。

在我的代码中,我有几个更新其他模型的挂钩(例如更改的审计日志)。您需要确保传递 options.transaction,以便在链中稍后出现错误时回滚任何更改。

此示例访问由 other_model 键入的另一个 table。当钩子 运行 模型应该都已经注册到 Sequelize。

module.exports = function Order(sequelize, DataTypes) {
  const Order = sequelize.define(
      'order',
      { /* columns */ },
      {
        hooks: {
          beforeUpdate: async function(order, options) {
            // get the transaction, if it is set
            const { transaction } = options;

            // use sequelize.models and make sure to pass the 
            // transaction so it is rolled back if there is an error
            await sequelize.models.supplier.increment(balance, {
              where: { id: order.supplierId },
              transaction,
            });
          },
        },
      },
  });

  return Order;
}