首页 > 解决方案 > 如何在 sequelize 钩子中运行另一个模型查询?

问题描述

下面是我在 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;
};

标签: node.jsexpresssequelize.js

解决方案


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

此示例访问另一个以 为键的表other_model。当钩子运行时,模型应该已经全部注册到 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;
}

推荐阅读