Comments on many tables database design issue

后端 未结 5 969
予麋鹿
予麋鹿 2021-01-07 05:57

I have tables:

Articles{...}
Recipes{...}
Notifications{...}
Photos{...}

And I need to implement \'user comments\' feature (like facebook).

5条回答
  •  鱼传尺愫
    2021-01-07 06:36

    You could create another table CommentableEntity (although call it something better). Each of the rows in your tables (Articles, Recipes etc.) would have a reference to a unique row in this table. The entity table might have a type field to indicate the type of entity (to aid reverse joining).

    You can then have a Comment table that references CommentableEntity, in a generic fashion.

    So for example you'll end up with the following tables:

    Articles
    -----------------
    Article_id
    CommentableEntity_id (fk, unique)
    Content
    ....
    
    Recipes
    -----------------
    Recipe_id
    CommentableEntity_id (fk, unique)
    Content
    ....
    
    CommentableEntity
    -----------------
    CommentableEntity_id (pk)
    EntityType (e.g. 'Recipe', 'Article')
    
    Comment
    -------
    Comment_id (pk)
    CommentableEntity_id (fk)
    User_id (fk)
    DateAdded
    Comment 
    ...etc...
    

    You can add the CommentableEntity record every time you add an Article/Recipe etc. All your comment-handling code has to know is the CommentableEntity_id - it doesn't care what type of thing it is.

提交回复
热议问题