I'm making a full-stack web application and am trying to write as much logic in the database as possible.
I have a comment system like
1
/ \
2 3
/ \
4 5
that I'm representing like
Comments
===============
id | ...
---------------
1 | ...
2 | ...
3 | ...
4 | ...
5 | ...
CommentTree
===================================
id | ancestor | descendant | ...
-----------------------------------
1 | 1 | 1 | ...
2 | 1 | 2 | ...
3 | 1 | 3 | ...
4 | 1 | 4 | ...
5 | 1 | 5 | ...
6 | 2 | 2 | ...
7 | 2 | 4 | ...
8 | 2 | 5 | ...
9 | 3 | 3 | ...
10 | 4 | 4 | ...
11 | 5 | 5 | ...
and I'm wondering how I can set up so that when a comment is deleted, all its descendants are deleted. I know how to set it up to delete the references to the ancestor-descendant relationship when the ancestor is deleted:
FOREIGN KEY (ancestor) REFERENCES Comments(id) ON DELETE CASCADE
but how can I make that action trigger that the descendant comment to be deleted as well?
In other words, the following chain of events occurs
- Comment deleted
- All rows in tree with ancestor equal to that comment's id are deleted
- All comments whose ids are equal to the descendants deleted in step 2 are deleted
I have steps 1 and 2 down, but how can I work step 3 in there? Do I have to write a procedure that gets triggered when each tree element is deleted? Can you show me an example of how this would look?