`createMany` should return the created records
See original GitHub issueInitially brought up here: https://github.com/prisma/prisma/issues/4998#issuecomment-787206842
Problem
The fact that the createMany
API does not return the created records (which should be possible for Postgres) makes it difficult/impossible to use in some circumstances, meaning we must fall back to raw SQL. Here’s an example.
Let’s say I have these two tables
CREATE TABLE IF NOT EXISTS post (
"id" SERIAL PRIMARY KEY,
...
);
CREATE TABLE IF NOT EXISTS comment (
"id" SERIAL PRIMARY KEY,
"postId" INTEGER NOT NULL REFERENCES post ("id") ON DELETE CASCADE,
...
);
Let’s say I want to create many posts and many comments. The data to be created could be represented like so: Array<{post: PostData, comments: Array<CommentData>}>
. If createMany
returned the created data, I could do something like this:
const inputs: Array<{post: PostData, comments: Array<CommentData>}> = [...];
const posts = prisma.post.createMany({data: [...]});
const commentCreateData = inputs.map((input, index) => input.comments.map((commentData) => ...))).flat();
prisma.comment.createMany({data: commentCreateData});
However, since createMany
does not return the created data, it is difficult to create many posts and then create many comments linked to those posts in an efficient manner. The remaining options are to create records one-by-one or use raw SQL. Using a combination of createMany
and findMany
is possible if you manually specify IDs, but does not work if you rely on Postgres (or some other DB) to generate IDs by default.
Suggested solution
createMany
should return an array of created records (like how create
returns the single created record).
Alternatives
- Use
create
(inefficient if creating many records) - Use raw SQL (efficient but inconvenient)
- Use
createMany
+findMany
(only works if you manually specify IDs, and also less efficient than ifcreateMany
returned created records)
Additional context
Personally, I’ve used raw SQL as a workaround since it’s the most efficient alternative.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:262
- Comments:50 (3 by maintainers)
Top GitHub Comments
Currently using this type of abstraction for handling this. If
createMany
would return the array of entities, that would be great.Hey there. Unfortunately no plans yet because not all natively databases support this and we’re not quite at the stage where we can make fine-grain adjustments to our APIs depending on the database.
For now, we recommend the suggestion that @GauravRajSharma mentioned. Please let me know if you run into any problems with that approach and we can try to find alternatives for you.