I highly recommend that you read this article about storing hierarchical data in a database . Two algorithms are discussed there, and one of them may be appropriate depending on your needs.
Affection List Model
This is what you have. Each node of the tree stores a link to its parent, and you can recursively determine the path to the node by selecting each level of the tree and iterating through the nodes. This is easy to implement, but the disadvantage is that recursive queries are required to determine the specific path to the node. If your tree is subject to a lot of changes (i.e., Writes), this is a good way, since dynamically detecting each node works well with an ever-changing tree. If it reads-heavy, you have some recursion overhead.
Changed order tree traversal
My favorite, this is a very neat algorithm. Instead of storing a link to the parent (which you can do anyway for convenience), you store a link to the "left" and "right" nodes for each given node. The entire path to the node can be defined in a single select request or, conversely, all the children of the node. The algorithm is harder to implement, but it has performance advantages for trees with high strength. The disadvantage is that every time a node is moved or added, it is necessary to recalculate all branches of the tree, so it may not be suitable for datasets with a record.
In any case, hope the article gives you some ideas. This one good.
source share