Search code examples
database-designrelational

Best Practice for relationships shared among multiple tables


I keep running into this design problem, and I'm not happy with my solution so far. The problem is this:

I have two or more entities, like People and Dogs, and they both have a relationship with a Notes table, that stores a message field and some meta data about the message like maybe the author.

1) First option is to not enforce the Foreign Key. That way I can store the FK like peopleId or dogId (no matter what it is) in the same generic FK field like fkId. Then I'd store the tableId in another column--one can hope to get the table id from the RDMS meta data, but you could also have a dirty hack and explicitly make a table full of tables that you'd have to update manually. This is really sloppy and I just mention it for completeness.

2) Clone the Notes table for each table that needs it, like PeopleNotes, DogNotes, CatNotes, etc. This creates a pretty major normalization problem.

What have other people done in situations like this?


Solution

  • If these are your 'model' tables:

    dog Table:
    id | name | ...
    1  | Rex
    2  | Fido
    
    people Table:
    id | name | ...
    1  | Bob
    2  | Alice
    
    notes Table:
    id | text | ...
    1  | A nice dog.
    2  | A bad dog.
    3  | A nice person.
    

    You can have the relationships kept in separate tables:

    dog_note Table:
    dog_id | note_id
    1      | 1
    2      | 2
    
    note_people Table:
    person_id | note_id
    1         | 3
    2         | 3
    

    I usually stick with the convention of using the alphabetical order of my models for naming the relationship tables.