Fix major performance issue.

So I fixed it from generating large queries and from running it multiple times by caching results and relationship keys.
Add unit test for performance issue.