mysqldatabase-design

link roles to several permissions to manage user roles in a database


I'm creating a website managing users and their permissions. I want to assign a user a certain role, and have each role contain one to several permissions that can be read easily by my script.

I want to set up my database to manage such roles easily and efficiently.

I picture tables users, roles, and permissions. I could give each user a role id that joins the roles table.

How can I link roles to several permissions?


Solution

  • I just don't know how I can link roles to several permissions.

    You use a join table: role_id and permission_id to identify what permissions are associated with which roles

    EDIT:

    Example tables

    ROLE Table

    Role_ID Role_Name
    1       Standard User
    2       Super User
    3       Guest
    

    PERMISSION Table

    Permission_ID Permission_Name
    1             View User List
    2             Update Own User Account
    3             Update Any User Account
    

    ROLE_PERMISSION Table

    Role_ID Permission_ID
    1       1    // Role 1 (Standard User) grants View User List
    1       2    //        and Update Own User Account
    2       1    // Role 2 (Super User) grants View User List,
    2       2    //        Update Own User Account,
    2       3    //        and Update Any User Account
    3       1    // Role 3 (Guest) grants View User List
    

    Listing the permissions for a specified Role_ID

    select R.role_id,
           P.permission_id,
           P.permission_name
      from role R,
           permission P,
           role_permission RP
     where RP.permission_id = P.permission_id
       and RP.role_id = R.role_id
       and R.role_id = 1