Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
Prisma - create Post with N amount of Categories (explicit Many-to-Many)

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],
            },
          },
        },
      ],
    },
  },
})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda