Been struggling with this on an architectural level.
I have an object which can be commented on, let’s call it a Post. Every post has a unique ID.
Now I want to comment on that Post, and I can use ID as a foreign key, and each PostComment has an ItemID field which correlates to the Post. Since each Post has a unique ID, it is very easy to assign “Top Level” comments.
When I comment on a comment however, I feel like I now need a PostCommentComment, which attaches to the ID of the PostComment. Since ID’s are assigned sequentially, I can no longer simply use ItemID to differentiate where in the tree the comment is assigned. I.E. both a Post and a Post Comment might have an ID of ‘5’, so my foreign key relationship is invalid.
This seems like it could go on infinitely, with PostCommentCommentComment’s etc…
What’s the best way to solve this? Should I have a field in the comment called “IsPostComment” or something of the like to know which collection to attach the ID to? This strikes me as the best solution I’ve seen so far, but now I feel like I need to make recursive DataBase calls which start to get expensive.
Meaning, I get a Post and get all PostComments where ItemID == Post.ID && where IsPostComment == true
Then I take that as a collection, gather all the ID’s of the PostComments, and do another search where ItemID == PostComment[all].ID && where IsPostComment == false, then repeat infinitely.
This means I make a call for every layer, and if I’m calling 100 Posts, I might make 1000 DB calls to get 10 layers of comments each.
What is the right way to do this?
I’d say that you would just have PostComment, not PostCommentComment or anything beyond that.
All PostComments have a PostId, so when you load comments for that post, you just query by PostId.
All comments also have ParentId, which points to another comment (top-level comments will not have a ParentId). In this way, every comment can have comments on it to any depth, but the data remains flat in the database.
Once you load all comments with a given PostId, you can assemble the tree/hierarchy in memory using the ParentId property.