Kenmore
Kenmore

Reputation: 1595

Should a junction table for a many-to-many relationship have a surrogate primary key?

I'm working with mySQL and Laravel. I have two tables: users and groups. Each has an id field and a name field. I want users to be able to belong to many groups and vice versa; so I'm setting up a many to many relationship with a junction table: group_user.

My first thought is that it only needs two fields: user_id and group_id, both Foreign Keys. But something tells me I might need/want an id for this table too. I've seen it both ways in code examples across the internet and I just want to know what I would be missing by not having it.

I just can't think of how I would actually make use of it; since the table is just to relate two other tables.

Upvotes: 1

Views: 717

Answers (1)

Lajos Veres
Lajos Veres

Reputation: 13725

The artificial primary key can be very useful sometimes in your code. For example when you would like to delete a record you can use the same pattern as in the case of other tables. You have to pass only one id instead of the parts of the compound key.

Upvotes: 1

Related Questions