更新多对多关系 [英] Updating in a many-to-many relationship

查看:91
本文介绍了更新多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多对多表,用于存储用户可以拥有的每个允许角色的记录.如果用户更新了自己的角色(添加和删除),我该如何处理?

I have a many-to-many table that stores a record for each allowed role a user can have. If a user updates his roles (add, and removes) roles how should I handle this?

我应该先删除所有用户角色,然后添加所选角色吗?还是进行某种匹配?

Should I delete all the users roles first and then add the selected ones? Or do some sort of matching?

推荐答案

有很多方法可以给这只猫换皮,我可以想到一些技巧:

There are many ways to skin this cat, a few techniques I can think of:

1.删除所有角色并重新插入
这是简单明了的方法.删除用户的所有角色,然后重新插入.通常,用户仅属于少数几个角色(少于10个).另外,很有可能没有其他外键链接到此多对多表.

1. Delete all roles and re-insert
This is a straight-forward approach. Remove all the roles for the user and just re-insert. Normally the user only belong to a few roles (less than 10). Also, there is a good chance that no other foreign-keys link to this many-to-many table.

2.跟踪更改并仅应用更改
即使在这种情况下仅需一点点工作,但这项工作却更多,但效率更高.像ORMs这样的工具可以轻松跟踪和应用这些类型的更改.

2. Keep track of the changes and apply only the changes
This is more work but more efficient, even if just slightly in this case. Tools like ORMs makes tracking and applying these type of changes a breeze.

3.在用户进行更改时应用更改
在这种情况下,我认为当最终用户将用户与角色相关联时,应用数据库更改是可以接受的.也许这是一个本地数据库,并且每个事务都是短暂的.但是我想这是一个不太可能的情况.

3. Apply the changes as the user makes the change
In this case I assume that it is acceptable to apply the DB changes as the end-user associates the user to roles. Perhaps it is a local database and each transaction is short-lived. But I guess this is a unlikely scenario.

对于这种特殊情况,我认为删除并重新插入没有任何问题.

I don't think there is anything wrong for this particular case to delete and re-insert.

这篇关于更新多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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