Sequelize - 在关联的其他地方使用时防止破坏行 [英] Sequelize - Prevent destroying row when used somewhere else in association

查看:51
本文介绍了Sequelize - 在关联的其他地方使用时防止破坏行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试销毁关联某处使用的行时,有没有办法让 Sequelize.js 抛出异常?

作为例子,让我们有 Roles 表和 Users 表.它们具有关联 N:M,因此任何用户都可以拥有多个角色.

问题是当用户的角色很少并且包含的​​角色行被删除时.用户只是失去了这个角色.除非先删除关联,否则如何防止角色删除?

解决方案

你可以使用 onDelete 和 onUpdate 在关联中控制这个,就像这样:

User.hasMany(Roles, { foreignKey: "whatever", onDelete: 'restrict', onUpdate: 'restrict'});

手册的外键部分提到了选项 ...

Is there way to make Sequelize.js throw exception when I try destroy row what is used somewhere in association?

As example let's have table for Roles and table for Users. They have association N:M, so any user is able to have many Roles.

Problem is when user have few roles and row of included role is removed. User just loose this role. How to prevent role from removing unless association is removed first?

解决方案

You can control this in the association using the onDelete and onUpdate, like this:

User.hasMany(Roles, { foreignKey: "whatever", onDelete: 'restrict', onUpdate: 'restrict'}); 

The Foreign Key section of the manual mentions the options ...

这篇关于Sequelize - 在关联的其他地方使用时防止破坏行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆