我有以下关联:
Training.hasMany(Exercise, {
foreignKey: 'trainingId',
as: 'exercises',
});
Exercise.belongsTo(Training, {
foreignKey: 'trainingId',
as: 'training',
});
考虑到我有与记录 exercise1
相关联的记录 exercise2
和 training
。当我执行 training.setExercises([exercise2])
时,我希望 exercise1
被删除并保留 exercise2
,但相反,sequelize 对 exercise1
进行更新以将 trainingId
设置为 null。不是应该删除记录吗?如果这是预期的行为,我如何使它删除记录而不是将 FK 更新为空?
最佳答案
是的,这是预期的行为。根据 the docs :
Set the associated models by passing an array of persisted instances or their primary keys. Everything that is not in the passed array will be un-associated
请注意,其他所有内容都将取消关联,而不是删除。据我所知,除非您在表上配置了级联,否则关联函数将永远删除资源。
没有一个查询可以实现您想要的,但这样的查询就足够了。如果您的数据库支持,建议您在事务中执行以下操作。
// get existing associated exercises
const exercises = await training.getExercises();
// associate the new exercise
await training.addExercise(exercise2);
// delete the previously associated exercises
for (let i = 0, n = exercises.length; i < n; i++)
{
await exercises[i].destroy();
}
关于node.js - 使用 sequelize 删除关联记录而不是将 fk 设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63946420/