Reputation: 21
I'd like to assign a primary role to a user with many roles and I'm wondering what method is preferable, if any. Either to make a primary_role_id
column in the users table or add an is_primary
column in the pivot table:
Users:
id | name | primary_role_id here? |
---|---|---|
1 | alice | 2 |
2 | bob | 1 |
Roles:
id | name |
---|---|
1 | super |
2 | admin |
Role User:
user_id | role_id | OR is_primary here? |
---|---|---|
1 | 1 | true |
1 | 2 | false |
2 | 1 | false |
2 | 2 | true |
Upvotes: 0
Views: 305
Reputation: 33708
It is simple, but not quite that simple. What you really want is:
User
is permitted 1-to-n Roles
RoleUser
is primary
Therefore:
IsPrimary
indicator has to be in RoleUser
CHECK
Constraint on RoleUser
, that calls a Function, to ensure that there is just 1 IsPrimary
Role
per User
.User
is permitted 1-to-n Roles
User
has 1 primary Role
User
has the Role
in RoleUser
that is declared as PrimaryRoleId
.Upvotes: 2