How to connect the users table to the roles table (using the table user_roles)?

匿名 (未验证) 提交于 2019-12-03 08:28:06

问题:

I need to create a basic database for user authentication. So far, every user has a name, a password and a role. I've found this somewhere on the Internet, which looks quite promising:

create table if not exists users (   id int unsigned not null auto_increment,   username varchar(100) not null,   password binary(60) not null,   primary key(id),   unique(username) );  create table if not exists roles (   id int unsigned not null auto_increment,   role varchar(100) not null,   primary key(id),   unique(role) );  create table if not exists user_roles (   user_id int unsigned not null,   role_id int unsigned not null,   unique(user_id, role_id),   index(user_id) ); 

But... if I would create new users, how would I fill the user_roles table? I have a feeling there is some "automatic way" to do this, but I have totally no idea (being a database noob :-)). How could I somehow connect a user to a role?

回答1:

You would first populate the roles table. Then, add a user to the users table. Then, taking the ID from the users table, you want to associate it with an ID from the roles table inside of the user_roles table. Like so:

---- Users Table --------- ID | UserName | Password  1 | Test     | ***** --------------------------  ---- Roles Table --------- ID | Role  1 | Test_Role  2 | Another_Role --------------------------  ---- User Roles Table --------- UserID | RoleID      1 |      1      1 |      2 ------------------------------- 

This is done for a "Many To Many" relationship. It's also called "Normalizing" your database.



回答2:

For each user, you simply insert one row in the user_roles table for every role you want to assign to that given user. There's nothing automatic about it. It's a many-to-many relationship.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!