سؤال

Ok, so lets say you have a user definition with the following properties:

Username, Password, ...etc

And you map roles to users, e.g. admin, no_privileges, god_mode ;) etc

Why does every example I come across have these as separate tables? And then map users to the roles?

What I mean is, what is the practical point in it? There clearly must be something I'm missing, but can't you just have "Role" as a user property (or a list Roles for multiple roles? ), thereby keeping everything a lot cleaner...

Also, if roles are unlikely to change often - is it better to just have a class setup with a list of roles to privileges to reduce calls to the DB?

هل كانت مفيدة؟

المحلول

If all users have a single role then you don't really need another table. Having a mapping table sets up a many to many relationship allowing a single user to have multiple roles, and also the same role assigned to multiple users.

For example, if it was all in the User table, it wouldn't be possible to have the following:

user: bob, roles: user, super user user: joe, roles: user, admin

This is quite a common setup. In this scenario, everyone would typically have the 'user' role but gain additional privileges through other roles. In a traditional RDBMS you simply must have a many to many relationship to model this in a fairly normalized fashion, which requires a mapping table.

نصائح أخرى

Google "database normalization."

From a technical perspective, keeping roles in their own table reduces redundancy, prevents naming inconsistencies (since you must refer to this table by its primary key), allows a many-to-many relationship between users and roles, etc.

From a functional perspective, this allows users to have multiple roles. If you have a lot of privileges you need to manage, it wouldn't really make sense to define and maintain a role for every combination of privileges and then assign that single role to the appropriate users. It is much easier and more maintainable to define logical roles (collections of privileges that make sense given your requirements) and then assign these smaller roles to users. This way, if you need to grant or revoke a subset of privileges for a given user, you can simply add/remove them from a role via this table rather than redefining their entire role (and subsequently affecting everyone else who is also part of that role).

It is taking into account the possibility that a system may not have roles, and thus does not need that table. If you need roles than it is there for you.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top