3

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?

1
  • 6
    Please don't crosspost.
    – user7043
    Commented Aug 28, 2012 at 20:00

1 Answer 1

11

All you need is a PostID for each thing that a user writes, and a ParentPostID that's nullable and points to a parent PostID. If it's null, it's a Post, and if it's not null, it's a comment. Comments can have comments.

Basic tree structure.

Not the answer you're looking for? Browse other questions tagged or ask your own question.