I want to save and restore a tree structure in mysql database ?
I try to save it by adding "parent_id" field to reference the id of parent row. the parent but it can reference to each other and it is no logical , so i want to prevent two rows to reference parent_id to each other.
Topic is a bit brother than depicted issue, so I'll start with that, and then answer. I'm aware about some ways of storing tree in db:
root_id:level_id:another_level_id:parent_id:node_id
So the question is about first case, where it can happen we have a cycle. Note that just one node referring other is easy to catch, what if there are like 10 nodes involved?
Answer can be, that for any update that touches parent_id column we need trigger to check if current id is not used by any node as parent. In other words - go over parents checking if current id is not anywhere, before getting root node.
As a side note - maybe delete should be also addressed somehow? I mean - maybe we need to fix structure, or be sure we do delete all children?
Both above can be done by application, but since question is about database, my proposals stick to database.