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

StackOverflow https://stackoverflow.com/questions/23675404

  •  23-07-2023
  •  | 
  •  

Pregunta

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.

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top