Home > Enterprise >  Prisma - create Post with N amount of Categories (explicit Many-to-Many)
Prisma - create Post with N amount of Categories (explicit Many-to-Many)

Time:05-22

I have the most basic explicit Many-to-Many relation:

model Category {
  id              Int     @id @default(autoincrement())
  title           String @db.VarChar(24)  
  posts           PostCategory[]
}

model Post {
  id              Int     @id @default(autoincrement())
  title           String @db.VarChar(24)  
  categories      PostCategory[]
}

model PostCategory { 
  category        Category     @relation(fields: [categoryId], references: [id])
  categoryId      Int 
  post            Post @relation(fields: [postId], references: [id])
  postId          Int 

  @@id([categoryId, postId]) 
  @@unique([categoryId, postId])
} 

What I now try to accomplish is to create a new Post with n categories. So lets say we have an String array with n amount of category titles:

const myStringArray = ["Category1", "Category2", "Category3", ...];

How can I create one query that adds all of them to my new created post? If I put it in static it is not a problem, but how can I handle a list where I don't know the size?

const assignCategories = await prisma.post.create({
  data: {
    title: 'First Post Title',
    categories: {
      create: [
        {
          category: {
            create: {
              name: myStringArray[0],
            },
          },
        },
        {
          category: {
            create: {
              name: myStringArray[1],
            },
          },
        },
      ],
    },
  },
})

CodePudding user response:

You can use Array.map() to map each string element into an object of the required shape

const myStringArray = ['Category1', 'Category2', 'Category3'];

const assignCategories = await prisma.post.create({
    data: {
        title: 'First Post Title',
        categories: {
            create: myStringArray.map((title) => ({
                category: { create: { title } },
            })),
        },
    },
});

Array.map() docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

  • Related