vincent15000's avatar

What's the best way to manage an array field of roles in a table ?

Hello,

I don't want to use the Spatie package for the roles, I prefer to manage them myself.

Here is the context : several companies can connect to the app and manage their own data and their own collaborators who can access to the datas of their company. I thought about setting up a multitenancy app, but I'm not sure I really need it and you discouraged me to do that unless I have good knowledge about multitenancy --- and I don't have ---.

So I have created those two tables (I don't have any roles table, the roles are written in a configuration file).

members : id, company_id, user_id
roles : member_id, role_id

Here is my two questions.

  1. I realize that this is heavy to manage and I want to change it to one unique table where the roles field is an array containing the roles ids.
// Choice A
members: id, company_id, user_id, roles

Another way would have been this one where the superadmin, admin, manager, ... fields are booleans.

// Choice B
members: id, company_id, user_id, superadmin, admin, manager, trainer, student

What do you think about ? What would you suggest me ? I know that if I need to query for all students of a company, choice B will be better because otherwise I will need to filter through the array field values, but with choice B I will have less flexibility if I need to add a new role for example.

  1. For these roles, if I choose choice A, I have two possibilities : 0, 1, 2, 3, ... (roles numbers are in the configuration file) of directly write strings in the array (SUPERADMIN, ADMIN, MANAGER, TRAINER, STUDENT, ...).

Is there a best choice between number and strings ?

Thanks for your help.

Vincent

0 likes
3 replies
Tray2's avatar
Tray2
Best Answer
Level 73

Roles should be a single table with

  • id
  • role
  • description (optional)
  • timestamps (optional)

Then you should have a role_user pivot table connection the user to the role

  • id (optional but recommended)
  • role_id
  • user_id
  • timestaps (optional)

The user is connected to the company through a company_user pivot if the user can belong to many companies, otherwise add the company_id to the users table.

Now if a user can belong to multiple companies and have different roles on each then you need to add

  • company_id

to the role_user table as well.

1 like
vincent15000's avatar

@Tray2 Ok thank you. So your suggestion is similar to my choice A but with a role_id field instead of an array.

I think that you don't recommend the array for the same reason as mine ?

Tray2's avatar

@vincent15000 An array or an json field should no be used if it can be avoided, they are causing bad database designs.

1 like

Please or to participate in this conversation.