A self-referential hierarchy stores parent-child relationships when similar records belong in one table. A post can contain comments, and a comment can contain more comments without adding a table for every nesting level. section 11.7
Model the hierarchy by giving each row a reference to another row in the same table:
- Add a parent_uid field to Post and make it a foreign key to post_uid in that same table. section 11.7
- Treat rows with a NULL parent_uid as root content posts. section 11.7
- Treat rows with a non-NULL parent_uid as child comments that may reference either content or another comment. section 11.7
- Use the resulting one-to-many relationship to represent each row and its child rows. section 11.7
Nested comments
A content post is the root row. A comment points to that post, while a reply points to the comment. The database can support additional nesting; limiting comments to two levels remains an application decision. section 11.7
Use the table diagram to see how one Post table forms the content-and-comment hierarchy. section 11.7
For deeper traversal, combine SQLAlchemy and Python with common table expressions and recursion. section 11.12
