node.js - 如何在 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;
};
解决方案
在我的代码中,我有几个钩子可以更新其他模型(例如审计更改日志)。您需要确保传递,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;
}
推荐阅读
- jenkins - 作为可执行 Jar 的 Mulesoft 服务
- azure - azure devops 管道活动目录用户创建
- android - 如何使用数据绑定从适配器布局调用方法
- json - 将来自多行的 JSON 对象组合成一个对象
- powerbi - 如何通过 DAX 获得季度平均值
- entity-framework - EF Core 3.0 上的 EF Core 2.2 LINQ 查询问题
- css - 如何增加 mat-option 单元格大小
- c# - 静态变量会在方法调用之间在 ASP.NET MVC RestAPI 中保持活动状态吗?
- javascript - 在异步函数上调用 await 会引发错误
- php - php - cookie 的 empty() 函数不起作用