San*_*ndy 0 node.js express sequelize.js
下面是我在sequelize 中定义的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;
};
Run Code Online (Sandbox Code Playgroud)
在我的代码中,我有几个用于更新其他模型的钩子(例如审核更改的日志记录)。您需要确保传递 ,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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2396 次 |
最近记录: |