Ok I found that this was actually quite simple... just do it as usual insert and include the forign key id.

    const result = await prisma.posts.createMany([
      {
        ...postData,
       userId,
      },
    ]);
Answer from fotoflo on Stack Overflow
Top answer
1 of 1
2

Hi @MatheusGNachtigall 👋

Thank you for raising this question.

Prisma does not support the createMany operation with nested writes, which includes the connect operation for relations. The createMany operation is designed to create multiple records in a single model without handling relations. See this section of the documentation.

However, you can use the create operation to create a single record along with its relations in a nested write. For example, to create a Post and connect it to existing Category records by their unique identifier, you would use the following code:

const createPostWithCategories = await prisma.post.create({
  data: {
    title: 'Post 1',
    categories: {
      connect: [{ id: 'category-id-1' }, { id: 'category-id-2' }],
    },
  },
});

In your case, since you want to create multiple posts and connect them to existing categories, you would need to loop through your postsData array and call prisma.post.create for each post. Here's an example of how you might do this:

async function createPostsAndConnectCategories(postsData) {
  return Promise.all(
    postsData.map(postData =>
      prisma.post.create({
        data: postData,
      })
    )
  );
}

const postsData = [
  {
    title: "Post 1",
    categories: {
      connect: [{ name: "Category1" }, { name: "Category2" }],
    },
  },
  {
    title: "Post 2",
    categories: {
      connect: [{ name: "Category2" }, { name: "Category3" }],
    },
  },
  // Add more posts as needed
];

const createdPosts = await createPostsAndConnectCategories(postsData);

This approach will execute the creation of each post and its connections to categories in parallel, which may help with performance compared to a sequential loop. However, it's important to note that this could still be a time-consuming operation given the large number of records you mentioned.

If this answers your question, it would be great if you could mark this Discussion as answered to indicate that it has been resolved.

Otherwise please let us know how else we can help you further or close the Discussion if it was resolved in some other way 🙏

Discussions

Prisma CreateMany with a relation (connect)
Hi everyone, in Prisma is there a way to createMany with relation - using connect i assume? Basically this a million times: I read the documentation and there doesn't seem to be "nested createMany" but i think that's not that im doing (or is it? More on answeroverflow.com
🌐 answeroverflow.com
January 21, 2023
is it possible to have a connect clause within a createMany operation?
CreateMany while connecting to many · prisma prisma · More on answeroverflow.com
🌐 answeroverflow.com
July 28, 2024
How to createMany with a relation? Looping CREATE and getting "too many connections"?
hello! Let me see if i got this straight - I have what i believe to be a very simple issue: I create a batch of reports scores I create a bunch of scores in the batch Because you can't use crea... More on github.com
🌐 github.com
3
5
How to use connect inside createMany ?
const createEpisode = await prisma.episode.createMany({ data: [ ...episodes ] }) I want to connect season to each episode (many to many) model Season { id String @id @default(uuid()) number Int @de... More on github.com
🌐 github.com
1
1
April 27, 2023
🌐
Prisma
prisma.io › home › relation queries › relation queries › relation queries › relation queries
Relation queries (Concepts) | Prisma Documentation
Nested readsRelation load strategies (Preview)ExamplesWhen to use which load strategy?Include a relationInclude all fields for a specific relationInclude deeply nested relationsSelect specific fields of included relationsRelation countFilter a list of relationsNested writesCreate a related recordCreate a single record and multiple related recordsUsing nested createUsing nested createManyCreate multiple records and multiple related recordsConnect multiple recordsConnect a single recordConnect or create a recordDisconnect a related recordDisconnect all related recordsDelete all related recordsDe
🌐
Answer Overflow
answeroverflow.com › m › 1066271029569278042
Prisma CreateMany with a relation (connect)
January 21, 2023 - const result = await prisma.posts.create({ data: { user: { connect: { id: user.id, }, }, ...postData, }, }); const result = await prisma.posts.create({ data: { user: { connect: { id: user.id, }, }, ...postData, }, });
🌐
Answer Overflow
answeroverflow.com › m › 1267217559669837834
is it possible to have a connect clause within a createMany operation? - Prisma
July 28, 2024 - Hi @toasty 👋 Prisma Client does not support the createMany operation with nested writes, which includes the connect operation for relations. You can refer to the documentation for more details.
Find elsewhere
🌐
Prisma
prisma.io › home › prisma client api › prisma client api › prisma client api
Prisma Client API | Prisma Documentation
You cannot create or connect relations by using nested create, createMany, connect, connectOrCreate queries inside a top-level createMany() query.
🌐
Prisma
prisma.io › home › crud › crud › crud › crud
CRUD (Reference) | Prisma Documentation
const users = await prisma.user.createManyAndReturn({ data: [ { name: "Alice", email: "alice@prisma.io" }, { name: "Bob", email: "bob@prisma.io" }, ], });
🌐
Tericcabrel
blog.tericcabrel.com › many-to-many-relationship-prisma
Handle a Many-to-Many relationship with Prisma and Node.js
February 26, 2024 - import { Prisma, PrismaClient } from '@prisma/client'; const prisma = new PrismaClient({ errorFormat: 'pretty' }); const loadMovies = async () => { const moviesInput: Prisma.MovieCreateManyInput[] = [ { name: 'Avatar', releaseDate: new Date(2009, 11, 16) }, { description: "A soldier try to revenge his family's death", name: 'Gladiator', releaseDate: new Date(2000, 5, 20), }, { description: 'Our here united to save the world', name: 'Avengers', releaseDate: new Date(2012, 3, 25), }, ]; await prisma.movie.createMany({ data: moviesInput, }); }; const loadUsers = async () => { const usersInput: Prisma.UserCreateManyInput[] = [ { name: 'Bob', email: 'bob@email.com' }, { name: 'Alice', email: 'alice@email.com' }, ]; await prisma.user.createMany({ data: usersInput, }); }; const main = async () => { await loadUsers(); await loadMovies(); }; main().then();
🌐
Stack Overflow
stackoverflow.com › questions › 76829241 › connectorcreate-in-createmany-prisma-query
connectOrCreate in createMany prisma query? - Stack Overflow
Nested relations in createMany is not supported at the moment. ... You can loop over your records and use create with connectOrCreate.
🌐
YouTube
youtube.com › vlogize
Solving the Prisma CreateMany with Connect Problem - YouTube
Discover how to effectively use Prisma's `createMany` with `connect` in your Node.js applications. This post simplifies the solution for smooth development.-...
Published   March 18, 2025
Views   1
🌐
Reddit
reddit.com › r/node › help with prisma create many.
r/node on Reddit: Help with Prisma create many.
October 28, 2021 -

I want to be able to use prisma createMany in a nested object. Is this possible? Basically a deck has many sets and sets have many cards. I want to be able to create this all at once.

Like this:

        const deck = await context.prisma.deck.create({
          data: {
            sets: { createMany: { data: [...newSets, cards: { createMany: {data: [...newCards]}}] } },
          },
        });
🌐
YouTube
youtube.com › prisma
Bulk Inserting Data with Prisma's createMany Method - YouTube
New at Prisma 2.16 is the createMany method. This method allows developers to bulk insert data instead of looping over a dataset and creating records one at ...
Published   February 5, 2021
Views   28K
🌐
GitHub
github.com › prisma › prisma › issues › 5455
Create nested relations using `createMany()` and `createMany` · Issue #5455 · prisma/prisma
February 3, 2021 - As per my understanding await prisma.accoutns.createMany() works only on a single entity and not on sub-entities. hence i tried to use create along with createMany as mentioned in this ticket. #4998 but currently it is not working at sub...
Author   prisma
🌐
Prisma
prisma.io › home › many-to-many relations › many-to-many relations › many-to-many relations › many-to-many relations › many-to-many relations
Many-to-many relations | Prisma Documentation
// Create post with new category const post = await prisma.post.create({ data: { title: "How to be Bob", categories: { create: [ { assignedBy: "Bob", category: { create: { name: "New category" } }, }, ], }, }, }); // Connect to existing categories await prisma.post.create({ data: { title: "My Post", categories: { create: [ { assignedBy: "Bob", category: { connect: { id: 9 } } }, { assignedBy: "Bob", category: { connect: { id: 22 } } }, ], }, }, }); // Query posts by category const posts = await prisma.post.findMany({ where: { categories: { some: { category: { name: "New Category" } } } }, });
🌐
Stack Overflow
stackoverflow.com › questions › 76576540 › prisma-many-to-many-with-createmany
database - Prisma many-to-many with createMany - Stack Overflow
const createdPosts = await prisma.post.createMany({ data: posts.map(({ text, phones }) => ({ text, phones: { connectOrCreate: phones.map(phone => ({ where: { phone }, create: { phone } })) } })) });