associations - Sequelize ORM,Hooks 不与关联一起工作
问题描述
我有 2 个模型,一个 Department 和一个 Staff,它们通过 belongsToMany 关联关联起来。
现在,每当调用 staff.addDepartment 时,我都需要调用一个函数。我正在尝试使用钩子,sequelize 文档指出“当使用添加/设置函数时, beforeUpdate/afterUpdate 钩子将运行。”
但是经过一段时间尝试使其工作后,当调用 addDepartment 时,仍然没有调用钩子 'afterUpdate'
员工模型
module.exports = (sequelize, DataTypes) => {
const Staff = sequelize.define('Staff', {
workingLocation: {
type: DataTypes.STRING,
allowNull: true,
},
},
{
freezeTableName: true,
hooks: {
afterCreate: (instance, options) => {
console.log('\n\n\nSTAFF -> Hook associting staff to department: \n\n\n', staffDepartment);
},
beforeUpdate: (instance, options) => {
console.log('\n\n\n Before update model \n\n\n', staffDepartment);
},
afterUpdate: (instance, options) => {
console.log('\n\n\nAfter update model \n\n\n', staffDepartment);
},
},
}
);
Staff.associate = (models) => {
Staff.belongsTo(
models.Person,
{
foreignKey: {
allowNull: false,
},
onDelete: 'CASCADE',
}
);
Staff.belongsToMany(models.Department,
{
through: 'StaffDepartment',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
}
);
};
return Staff;
};
部门模型
module.exports = (sequelize, DataTypes) => {
const Department = sequelize.define('Department', {
name: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
acronym: {
type: DataTypes.STRING,
allowNull: true,
},
},
{
freezeTableName: true,
hooks: {
afterCreate: (staffDepartment, options) => {
console.log('\n\n\Department -> Hook associting staff to department: \n\n\n', staffDepartment);
},
beforeUpdate: (staffDepartment, options) => {
console.log('\n\n\n Department Before update model \n\n\n', staffDepartment);
},
afterUpdate: (staffDepartment, options) => {
console.log('\n\n\n Department After update model \n\n\n', staffDepartment);
},
},
}
);
Department.associate = (models) => {
Department.belongsToMany(models.Staff,
{
through: 'StaffDepartment',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
}
);
Department.hasMany(models.Course,
{
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
}
);
};
return Department;
};
我希望在员工模型上触发更新后挂钩的代码
Staff.findById(staff.id).then((s) => {
s.addDepartment(departmentId);
});
有人可以帮忙吗?
解决方案
I had a same problem but found a solution. When you make a association between tables you have to use the afterBulkUpdate
if you want to run a hook before update a record.
推荐阅读
- angular - 在进行 ng build --prod 时,jw-angular-pagination 抛出错误
- javascript - 如何在javascript中使用while循环打印数字
- python - 使用 eval 时如何使用 df.appen
- c++ - 如何在普通图像上使用 seshat 作为 seshat(C++ 中的数学表达式识别库)的输入?
- php - 贷款 计算逾期还款,每日 0.2% 拖欠
- php - PHP语法建议
- c# - 使用 MaterialDesignTheme WPF 时使用系统默认按钮的正确解决方案?
- sql - 检查列值并从同一个表中更新另一个列值
- go - gorm 无效的内存地址或 nil 指针取消引用
- ruby-on-rails - Rails 无法指定外键