Is there a way to `createMany` while one of the fi...
# orm-help
d
Is there a way to
createMany
while one of the fields is like a counter? For example, I need something like this:
Copy code
prisma.invoice.createMany({
  data: [
    { 
      name: invoice.name, 
      billerId: user.id, 
      invoiceNumber: prisma.invoice.count({where: { billerId: user.id }}) + 1
    }, 
    ... 
  ]
})
Perhaps there is a way for me to get all prisma.invoice.counts easily first.
Copy code
prisma.invoice.groupBy({
  by: ['billerId'],
  _count: true
})
From there, I could smartly create the invoiceNumber... I'd probably perform this in an interactive transaction. My only problem is that during this groupBy/createMany combo, I want to ensure that the tables remained locked or that I can assure the actions are atomic — I don't want invoices created that would invalidate the invoiceNumber (as I have a unique constraint on [billerId, invoiceNumber]) Does something like the following suffice for that?
Copy code
prisma.$transaction(async (tx) => {
  const invoiceCountsForBiller = await tx.invoice.groupBy({
    by: ['billerId'],
    _count: true
  })

  await tx.invoice.createMany({
    data: {[
      {
        // ... incorporate invoiceCountsForBiller into logic
      }
    ]}
  })
})
I guess I would need to leverage the Serializable Isolation Level if I truly want to make this work. Is that right?