Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

186
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda