mysql 数据库角色_用户系统-MySQL数据库中的多个角色

bd96500e110b49cbb3cd949968f18be7.png

So I am in the process of attempting to create a basic user system and within this system I want users to be able to have multiple roles.

Say for example I have the roles as follows: Administrator, Events Organiser, Donator

What is the best way to assign these multiple roles to a user and then check if they have any of these roles for showing certain permissions.

If it was only one role per person then it wouldn't be a problem as I'd just assign say Administrator = 10, Organiser = 5 and Donator = 1 and then do an if statement to check if the MySQL data is equal to any of those three numbers.

I can't imagine there is a way to add a MySQL Field and fill it with say "Administrator,Donator" and therefore that user would have both of those roles?

Is it just a case of I would need to create 3 separate fields and put a 0 or a 1 in those fields and check each one separately?

解决方案

Use multiple tables and join them:

User

--------------

id name

1 test

Role

--------------

id name

1 Donator

2 Organizer

3 Administrator

User_Role

--------------

id user_id role_id

1 1 1

2 1 3

SELECT * FROM User u

LEFT JOIN User_Role ur ON u.id = ur.user_id

LEFT JOIN Role r ON ur.role_id = r.id

WHERE r.name = "Administrator";

The query is easier if you know you only have 3 roles and they are easy to remember.

SELECT * FROM User u LEFT JOIN User_Role ur ON u.id = ur.user_id WHERE ur.role_id = 3;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值