David Ilizarov
10/13/2022, 8:32 PMcreateMany
while one of the fields is like a counter?
For example, I need something like this:
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.
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?
prisma.$transaction(async (tx) => {
const invoiceCountsForBiller = await tx.invoice.groupBy({
by: ['billerId'],
_count: true
})
await tx.invoice.createMany({
data: {[
{
// ... incorporate invoiceCountsForBiller into logic
}
]}
})
})
David Ilizarov
10/13/2022, 8:52 PM