【发布时间】:2018-10-23 07:35:59
【问题描述】:
我有 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 模型上触发 afterUpdate 挂钩的代码
Staff.findById(staff.id).then((s) => {
s.addDepartment(departmentId);
});
有人可以帮忙吗?
【问题讨论】:
-
你不应该期待
afterCreate而不是afterUpdate吗? -
当我调用 s.addDepartmento() 时,已经创建了人员,因此 afterCreate 挂钩在创建人员时触发,而不是在将部门添加到人员时触发。我想要一个在您添加关联对象时触发的钩子...
-
您好,您找到解决方案了吗?我也有类似的情况,如果你知道答案,我会从你的知识中受益。谢谢。
标签: associations sequelize.js hook