Domanda

So, i'm currently working with a database system where a user can register, login and update his/her details whenever. The database includes 5 roles:

1. Public
2. Member
3. Moderator
4. Coordinator
5. Admin

I want to be able to assign multiple roles to my users. For example, the Admin can also be a member. Therefore in the database it should show:

User_id    |    Role_ID
------------------------
user1      | 2, 5

^ is it possible to add multivalued id's in postgresql?

È stato utile?

Soluzione

You can use filed of type array to store list of values. However I think that there is much better way to organize what you want.

Make one table: role_names and another roles, like that:

CREATE TABLE role_names
(
  id serial NOT NULL,
  name text NOT NULL,
  CONSTRAINT role_names_pkey PRIMARY KEY (id),
  CONSTRAINT role_names_name_key UNIQUE (name)
);

CREATE TABLE roles
(
  user_id bigint NOT NULL,
  role_id bigint NOT NULL,
  CONSTRAINT roles_pkey PRIMARY KEY (user_id, role_id),
  CONSTRAINT roles_role_id_fkey FOREIGN KEY (role_id)
      REFERENCES role_names (id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE RESTRICT
);

Now in the table role_names you put all the roles that you want to have. In the table roles, you can assign or delete any number of roles to any user. Also you can search in table roles for specific users or specific roles - much neat and faster than searching into arrays I think.

Feel free to add FK constraint for the user_id field too.

Altri suggerimenti

Yes, you can use int array to store list of roles.

Here's related question -Junction tables vs foreign key arrays?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top