Help Needed with Nested CreateMany!
Hi everyone,
I’m currently working on an API route to handle a POST request that does the following:
1. Accepts a single classroomId.
2. Retrieves all students in the classroom via memberships.
3. Creates an AssignmentSet for the classroom.
4. Iterates over the students to:
• Create an Assignment for each student.
• Create a Portfolio for each student.
• Connect the Assignment to the AssignmentSet.
I’m encountering issues with Prisma’s lack of support for nested CreateMany. Could anyone provide guidance or workarounds to achieve this functionality?
Creating the records one by one is too slow when there are potentially hundreds of students to iterate over.
Thanks for any suggestion/help!
7 Replies
Here’s the minimal version of my Prisma schema:
I had to separate it due to too much text limitation.
Consider creating two bulk operations:
- Create all the students' assignments
- Create all the students' portfolios
The flow of your code could then look something like this:
There will still be four DB calls, but better than N calls. Let me know if this helps.
@testas
Thanks for the suggestion. The cavieat with your approach is, createMany doesn't return the records. B\ut I re-read the docs and found this https://www.prisma.io/docs/orm/prisma-client/queries/crud#create-records-and-connect-or-create-related-records
It seems like a more efficient way to go about it!
It seems like a new thing, as it's only available at 5.14
CRUD (Reference) | Prisma Documentation
How to perform CRUD with Prisma Client.
Yes,
createManyAndReturn
is new as of 5.14.0
🙂I'm concerned that returning tons of records can be very costly/inefficient. I don't see an option to select specific properties to return using createManyAndReturn, but maybe i'm missing it? is there a way to for example select to return only IDs?
Ah, we should probably make that more clear.
select
is available: https://www.prisma.io/docs/orm/reference/prisma-client-reference#createmanyandreturnPrisma Client API | Prisma Documentation
API reference documentation for Prisma Client.
super pseudocode: