Domanda

How would I setup a groups table with following relationship with a list of user:

For example, lets say I have table of users:

              user_list
-----------------------------------
first_name | Last Name  | user_id |
-----------------------------------
   john    | Appleseed  |  4      |
   Jasmin  | Applejuice |  6      |

Now I want to create a groups table. How can I create a table where users can be included in a group, or multiple groups. For example, John is included in the Apple_group but also included in the Orage_group. Jasmin is only included in the Orange_group:

                        groups
----------------------------------------------------
   group_name    | included_users_ids  | group_id  |
----------------------------------------------------
   Apple_group   |       4             |   1       |
   Orange_group  |       4, 6          |   6       |

Assuming the user_list table already exists, how would I setup the groups table? Furthermore I've read (see link below) that I shouldn't include multiple values in a single column.

Inserting a foreign key with multiple values

So, my questions are:

  1. What would be the appropriate way to setup the groups table?

  2. What would the SQL be for doing so?

  3. How would this then be handled with PHP when wanting to set a user to a group?

È stato utile?

Soluzione

You need to create a third table, referred to as a "join table".

users (
  id,
  name
);

groups (
  id,
  first_name,
  last_name
);

groups_to_users (
  user_id,
  group_id
);

Then create an entry in the groups_to_users table for every group a user is a member of (or, you could say it another way, one entry for every user that's in a group). This is an n:n relationship (many-to-many). If you search for "database normalization", as I mentioned to you in an answer to a previous question, you'll learn all about this stuff.

If you want to get all of a user's groups, you'd do something like:

SELECT g.* FROM groups_to_users gtu
LEFT JOIN groups g ON gtu.group_id=g.id
WHERE gtu.user_id = :UserId

If you wanted to get a group's users, you'd do:

SELECT u.* FROM groups_to_users gtu
LEFT JOIN users u ON gtu.user_id=u.id
WHERE gtu.group_id = :GroupId
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top