问题
I've a relationship table for my many-to-many entities.
author_id | book_id
Do I need to add relation_id? I should be able to identify using both id.
Thank you
回答1:
Since you're using Doctrine, try not to think too much on the RDBMS level (at least, not most of the time).
If you have two Entities with a ManyToMany relationship, you should forget about the surrogate key. In fact, you should pretty much ignore the fact that the relationship table exists. You simply have two related entity types.
Now, if you need to store metadata about the relationship itself (for instance the date a badge was awarded to a user), you're going beyond a simple ManyToMany, and you need to model that relationship yourself -- by creating a new kind of entity (a UserBadge, for instance). That entity, of course, would have an id.
You're using an ORM, think about entities, not about tables (most of the time)!
回答2:
Most of the time in a joinn table like this just setting both as a combined PK is fine.
回答3:
You never need a surrogate key because you can always in principle use some other key instead.
In your question I don't think you mean "relational table", much less "relation". What I think you mean is "a table with more than one foreign key". Tables with more than one foreign key are not different to other tables and the design principles for them don't need to be different either. Choose the keys on the same basis you would for any other tables.
回答4:
I prefer having a single column auto-inc key on every table. It makes deleting and updating much simpler.
回答5:
You don't need to add a surrogate key. I would not.
回答6:
There are two issues here.
You DO need a unique constraint on the book/column combination to prevent duplicates. You have to do this even if you put on an auto-inc surrogate key.
Second, many frameworks these days don't know how to deal with anything except an integer key, so you may want to ALSO put on the integer column. But in this case you would need both.
回答7:
You strictly don't need it, but it might be handy while playing on SQL console, especially if both identifiers of the pair are long and tiresome to type.
On the other hand, it breaks 3NF. If you're not careful you can end up with two records with different surrogate keys and same pair of (book_id, author_id)
values. You'll have two indices to ensure two uniqueness constraints; this will slow down inserts and updates.
Also you might want to avoid an extra column for efficiency. If your table has great many records, having an extra column will make caching it in memory less efficient, and joins using it will be slowed by disk I/O more often.
来源:https://stackoverflow.com/questions/5794120/do-i-need-to-create-surrogate-key-for-my-relationship-table