You might want to use CTEs for this instead. Take a look at blaze-persistence which adds support fort CTEs through a builder API.