views:

51

answers:

3

I have 2 tables - one storing user information (id, username, password) and the second one storing information about events (id, name, description, date, username(represents the user who created the event)). I would like to implement 'favourite events' functionality. This would allow the user to store his favourite events and later display them in a list. I am not sure how to implement this in terms of design. I need a simple solution. Something like storing the IDs of favourite events in a field in the user table. I am using mysql and php. Can anyone point me to the right direction?

+4  A: 

You want to have a table linking the foreign keys from the user and event tables.

Users Table:

id, username, password

Events Table:

id, name, description, date, username

Favorites Table:

id, user_id, event_id

This way you can easily access the list of favorite events.

SELECT events.name, events.description, events.date
FROM events, users, favorites
WHERE favorites.user_id = users.id
AND favorites.event_id = events.id
chills42
Why did you add `id` column in `Favorites` table? It's useless.
Crozin
Can you tell me how exactly the foreign keys relationship should look like?
Vafello
In user_id and event_id are the foreign keys in this example. As you can see in the SQL provided they relate back to users.id and events.id (primary keys).
chills42
A: 

What you need is the most classic and basic many-to-many relationship.

You'll need extra table (let's say: user_event_ref) that will store user and event ids.

User:
  id
  name

Event:
  id
  name

UserEventRef:
  user_id
  event_id

In usereventref each column is a Foreign Key, and both columns are parts of Primary Key.

Crozin
A: 

There's always the option to add a tiny-int field to the Events table flagging an event as a favorite. This doesn't violate normalization in that whether or not an even is a favorite has no effect on the other events. It has the added benefit of automatically deleting the event from favorites if the event is deleted.

If a sorting scheme is needed for the favorites you can still modify the events table in the same manner. If details about the "favorite" such as when it was added to the list etc is needed then you should use an additional table as suggested.

souLTower
Yes, but what if I have many users? Does your idea work if there are many users who will choose the same event or the user chooses multiple events?
Vafello
This doesn't work unless you want the favorites to be system-wide. I believe the intended functionality is for user-specific favorites lists.
chills42
The current design doesn't allow multiple users to be assigned to a single event. It supports one user to many events.
souLTower