我正在尝试创建一个钩子(Hook),在为记录创建主键后应该调用该钩子(Hook)。我正在尝试使用插入的列(包括主键)的组合来生成一个数字。实例钩子(Hook)似乎被调用,而全局钩子(Hook)没有被调用,但即使我看到钩子(Hook)被调用,字段仍然返回 null:
module.exports = function(sequelize, DataTypes) {
var store = sequelize.define('store', {
storenumber: DataTypes.STRING(30), //remove
storespecificationid: DataTypes.INTEGER,
storetypeid: DataTypes.INTEGER,
storename: DataTypes.STRING(20), //remove
address: DataTypes.STRING(30),
city: DataTypes.STRING(30),
state: DataTypes.STRING(30),
zipcode: DataTypes.STRING(30)
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
},
hooks: {
/*this is not getting called*/
afterCreate: function(store){
let strnumber = store.storetypeid + store.storespecificationid + store.id;
store.updateAttributes({ storenumber: strnumber });
}
}
}
});
/*
This seems to be called
store.afterCreate(function(store) {
let strnumber = store.storetypeid + store.storespecificationid + store.id;
store.updateAttributes({ storenumber: strnumber });
});
*/
return store;
};
有人可以阐明我做错了什么吗?
最佳答案
我认为你有一个额外的对象定义了 classMethods
尝试下面的架构
module.exports = function(sequelize, DataTypes) {
var store = sequelize.define('store', {
storenumber: DataTypes.STRING(30), //remove
storespecificationid: DataTypes.INTEGER,
storetypeid: DataTypes.INTEGER,
storename: DataTypes.STRING(20), //remove
address: DataTypes.STRING(30),
city: DataTypes.STRING(30),
state: DataTypes.STRING(30),
zipcode: DataTypes.STRING(30)
}, {
associate: function(models) {
// associations can be defined here
},
hooks: {
/*this is not getting called*/
afterCreate: function(store){
let strnumber = store.storetypeid + store.storespecificationid + store.id;
store.updateAttributes({ storenumber: strnumber });
}
}
});
关于node.js - 使用 Node.js Sequelize 和 Hooks 实现触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41898016/