gpt4 book ai didi

node.js - 如何在 sequelize 钩子(Hook)中运行另一个模型查询?

转载 作者:行者123 更新时间:2023-12-03 22:22:38 25 4
gpt4 key购买 nike

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

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;
};

最佳答案

在我的代码中,我有几个钩子(Hook)可以更新其他模型(例如审计更改日志)。您需要确保传递 options.transaction以便在链中稍后出现错误时回滚任何更改。
此示例访问另一个以 other_model 为键的表.当钩子(Hook)运行时,模型应该已经全部注册到 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;
}

关于node.js - 如何在 sequelize 钩子(Hook)中运行另一个模型查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64520922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com