Refactor query building in Relation