Lucas
Lucas

Reputation: 661

How to save multiple tables related to each other with Prisma

I'm working on a NestJS project and I have two tables (TABLE_1 and TABLE_2), TABLE_1 schema looks like this:

model TABLE 1 {
  id                            String @id @default(uuid())
  secondaryfield                String @unique @map("secondary_field") @db.VarChar(12)
  table_2                       Table_2[]
}

And table 2:

model TABLE 2 {
  id                           String @id @default(uuid())
  table_1_id                   String @unique @map("secondary_field") @db.VarChar(12)
  table_1                      Table_1 @relation(fields: [table_1_id], references: [id])
}

Since there's a FK on my table_2 that depends on table_1, and both of them will be saved at the same time, is there any way that allows Prisma to deal with this and save multiple fields (not only two like the example) with multiple relations between them? I'm using createMany() method as I usually save dozens of those at the same time.

Upvotes: 1

Views: 4678

Answers (1)

luisbar
luisbar

Reputation: 778

You can try out the following:

prisma.table2.create({
  data: {
    table1: {
      createMany: {
        data: [
          {
            secondaryfield: 'table1-1',
          },
          {
            secondaryfield: 'table1-2',
          },
        ],
      }
    }
  }
})

More info here

Upvotes: 2

Related Questions