node.js - 使用 sequelize 删除关联记录而不是将 fk 设置为 null

标签 node.js sequelize.js

我有以下关联:

Training.hasMany(Exercise, {
  foreignKey: 'trainingId',
  as: 'exercises',
});

Exercise.belongsTo(Training, {
  foreignKey: 'trainingId',
  as: 'training',
});
考虑到我有与记录 exercise1 相关联的记录 exercise2training 。当我执行 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/

相关文章:

node.js - 强制依赖使用特定的子依赖版本

javascript - 从 api 响应中获取 pdf 文件

javascript - webrtc 通过 websocket 客户端/服务器连接问题

node.js - node.js FS无法从letencrypt读取证书

sequelize.js - Sequelize : Column not found immediately after creation

sequelize.js,计算关联项的数量

sql - 如何从 PostgreSQL 中的另一个表插入对 UUID 的引用?

node.js - 输入 Angular 找不到名称错误

javascript - 无法使用 Sequelize 在架构 (postgresql) 中关联模型

node.js - Sequelize 是否有办法查找或选择字段的子集?