There are several types of objects in a system, and each has it’s own table in the database. A user should be able to comment on any of them. How would you design the comments table(s)? I can think of a few options:
- One comments table, with a FK column for each object type (ObjectAID, ObjectBID, etc)
- Several comments tables, one for each object type (ObjectAComments, ObjectBComments, etc)
- One generic FK (ParentObjectID) with another column to indicate the type (‘ObjectA’)
Which would you choose? Is there a better method I’m not thinking of?
@palmsey
Pretty much, but the variation on that pattern that I’ve seen most often gets rid of
ObjectAIDet al.ParentIDbecomes both the PK and the FK toParents. That gets you something like:ParentsParentIDObjectAParentID(FK and PK)ColumnFromA NOT NULLObjectBParentID(FK and PK)ColumnFromB NOT NULLCommentswould remain the same. Then you just need to constrain ID generation so that you don’t accidentally wind up with anObjectArow and anObjectBrow that both point to the sameParentsrow; the easiest way to do that is to use the same sequence (or whatever) that you’re using forParentsforObjectAandObjectB.You also see a lot of schemas with something like:
ParentsIDSubclassDiscriminatorColumnFromA (nullable)ColumnFromB (nullable)and
Commentswould remain unchanged. But now you can’t enforce all of your business constraints (the subclasses’ properties are all nullable) without writing triggers or doing it at a different layer.