Reduce number of database queries when generating tree