我需要创建一个用于用户身份验证的基本数据库。到目前为止,每个用户都有自己的名字、密码和角色。我在网上找到了这个,看起来很有前景:
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)
);
但是。。。如果我要创建新用户,我将如何填充user_roles
表?我有一种感觉,有一些"自动的方法"可以做到这一点,但我完全不知道(作为一个数据库noob:-))。如何以某种方式将用户连接到角色?
您将首先填充roles
表。然后,将一个用户添加到users
表中。然后,从users
表中获取ID,希望将其与user_roles
表内部的roles
表中的ID相关联。像这样:
---- 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
-------------------------------
这样做是为了建立"多对多"的关系。它也被称为"规范化"你的数据库。
对于每个用户,只需在user_roles表中为要分配给该给定用户的每个角色插入一行。这并不是自然而然的,而是一种多对多的关系。