Optimized queries to reduce n+1 problem