-
Notifications
You must be signed in to change notification settings - Fork 2.1k
createMany() should return the created records #8131
Description
Initially brought up here: #4998 (comment)
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 ifcreateManyreturned created records)
Additional context
Personally, I've used raw SQL as a workaround since it's the most efficient alternative.