If I have a self-relation on my user model which i...
# orm-help
j
If I have a self-relation on my user model which is one-to-many, how do I best loop through that entire tree? It feels like it's bad performance to run a query for every single customer and go through one-by-one
r
@Jonas Rothmann 👋 Could you explain your use case for looping?
j
Copy code
const getParams = (id: number) => ({
  where: {id},
  select: {id: true, otherCustomers: { select: { id: true, otherCustomers: true } }}
})

ctx.log.debug('init customerTree')
const baseCustomer = await ctx.prisma.customer.findUnique(getParams(args.id))
if(!baseCustomer) return null

const customers: any[] = []

type TraverseCustomer = CustomerType & { customer: CustomerType | null; otherCustomers: TraverseCustomer[]; }
async function traverse(node: TraverseCustomer) {
  node?.otherCustomers.forEach(customer => {
    customers.push(customer)
    if(customer.otherCustomers) {
      const subCustomer = await ctx.prisma.customer.findUnique(getParams(customer.id))
      ctx.log.debug(JSON.stringify(subCustomer, null, 2))
      traverse(subCustomer)
    }
  })
}
traverse(baseCustomer)
This is what I've come up with, but for very deep or/and wide trees it does query the db a lot of times
r
Does this just find
subCustomers
for all the customers?
j
No it just takes in one customer, and traverses its children which are customers and loops through the tree that way
I just added async await where it was missing, and it works but its more if its best optimized for performance
r
Ohh, in that case this is the only option. You can run requests in parallel for all the nodes to make things faster for now. We have a request for the same here so it would be great if you could add a 👍 so that we know the priority for this 🙂