Junior — Middle
How are multiple roles assigned to a single user in a database?
sobes.tech AI
Answer from AI
In a database, a many-to-many relationship between user and role tables is typically used to assign multiple roles to a single user.
Example structure:
userstable — stores user data.rolestable — stores possible roles.user_rolestable — links users and roles, containing pairs ofuser_idandrole_id.
This approach allows a user to have multiple roles, and a role to belong to multiple users.
Example SQL for creating the linking table:
CREATE TABLE user_roles (
user_id INT,
role_id INT,
PRIMARY KEY (user_id, role_id),
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (role_id) REFERENCES roles(id)
);