Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading