Hello :wave: Is there a way to obtain the ids of ...
# orm-help
a
Hello đź‘‹ Is there a way to obtain the ids of the records I create with
createMany
? Something like this:
Copy code
const result = await prisma.payment.createMany({
  data: [...]
});

const createdPayments = await prisma.payment.findMany({
  where: {
    id: {
      in: result.ids, // THIS IS NOT POSSIBLE
    },
  },
});
Any possible workarounds?
âś… 1
t
I think only what we can do without modifying db is using create api for each records instead of createMany or providing specific ids (not prisma or db auto generated) to each records and use them. If api return always many created records’ ids, it’s inconvenient because second query’s needed to acquire them and it affects performance even if users are not using them. In other tuning performance technique, add some unique random id(like uuid v4) column to your table and giving same value each batch records and where specifying it as condition. Furthermore, you can create association with parent model and create them as children’ records using parent’s create api and specifying include like that.
Copy code
const result = await prisma.create({
  include: {
    children: true,
  },
  data: {
    children: {
      createMany: {
        data: [...]
      }
    }
  }
})
const ids = result.children.map(v => v.id) // This should be possible
a
Ohh I see. I think what would work best for me is specifying the ids of created records beforehand. I'm using cuid's, do you know if I can just use the library to generate them?
t
I think anything way to generate it is ok if well-tested and there’re many users when using random id generator like cuid and uuid because their algorithm should obey conformance to specification and identical to one located internal prisma, unfortunately it doesn’t reveal from
@prisma/client
lib as long as I know (Not clearly, I previous tried to find and reached this code written by rust for any programming language). Maybe you can use this, too. https://github.com/paralleldrive/cuid
n
Just to add, we have a Feature Request for returning records in
createMany
here: #8131 If you could add a 👍 to the request then it would help our product team in prioritising it. Also, here’s a workaround which you can use meanwhile.
t
@Nurul Is there performance difference about workaround? Is not
createMany
batch insert? (Sorry, there is as I expected, written in the thread’s alternatives.)
n
There won’t be much performance difference. You are correct
createMany
also does batch inserts so the behaviour would be the same. I was just providing an alternative way of achieving the same thing. 👍