Modelling heirarchical data is a solved problem with various solutions, including Adjacency List, Nested Set, Closure Table, etc. This is a great resource that dives into this m