In my application a user can post comments against either a post or a reply to a post. This is NOT the same as nested comments as the reply is a different table to the comment. I guess this is very similar to the way in which StackOverflow works.
I’m confused about how to link it though as what would the foreign key be? As normally I’d just put post_id in the comments table but I also need reply_id to link it to the answer IF its linked to that rather than the actual post. Although I guess I’d need both in that instance so to link to the post and the reply on that post although the reply itself is already linked… confusing right?
What’s the best way to do this? Thanks
POSTS
id
title
content
datetime
REPLIES
id
datetime
content
post_id
COMMENTS
id
datetime
content
post_id
reply_id
There are a couple of ways you can do this. One would be to allow COMMENTS.reply_id to be zero, or -1, or some other code that indicates that the comment isn’t related to a reply (sorry, I try to avoid NULLs at all costs!). The other way would be to replace the post_id and reply_id columns with two columns as follows:
There are caveats with both approaches, the chief being how to enforce referential integrity.
Hope this helps. Not exactly 3rd normal form but it will get the job done.