I've been stuck doing this in a very inefficient way and really want to know if there's some design pattern that solves this because it seems like a pretty common problem to have.
I have a system where I have a "world" class then that class has a list of town objects then the town has a list of buildings and buildings have a family. It's simple to for example, know what buildings a town has since the towns have all buildings in a list but what I always end up needing is a way for the building to know what town it is in for example. This can be done by giving buildings a town variable to keep that saved but I have to keep making sure that gets set properly for every stage in the chain which makes a mess of the code. It also messed up saving cause it saved a building in the town's building list but when saving the buildings data, had to save the town's data again since the building has that variable, creating a loop.
I've also tried making static methods that can be reached anywhere that say, a building can use and it will search through all towns until it finds where the building belongs, but that seems very inefficient to me and I've heard the same from others.
Lastly I've tried giving all of these things an ID but that still makes them have to search what "parent" has their ID.
Is there some way of doing this a more correct way? I have a hard time finding good search terms for it so I finally decided to just ask for guidance.