Home > Blockchain >  How to link many to many items in Prisma without duplicates
How to link many to many items in Prisma without duplicates

Time:02-26

I have many to many relationships between Product and Menu.

model Product {
  id    Int    @id @default(autoincrement())
  name String
  price Float
  description String?
  product_category ProductCategory @relation(fields: [category_id], references: [id])
  category_id Int

  menus MenuProducts[]

  created_at DateTime @default(now())
  updated_at DateTime @updatedAt

  @@map("products")
}

model Menu {
  id    Int    @id @default(autoincrement())
  name String
  products MenuProducts[]

  created_at DateTime @default(now())
  updated_at DateTime @updatedAt
  @@map("menus")

}

model MenuProducts {
  menu_id Int
  menu Menu @relation(fields: [menu_id], references: [id])

  product_id Int
  product Product @relation(fields: [product_id], references: [id])


  created_at DateTime @default(now())
  updated_at DateTime @updatedAt

  @@map("menu_products")

  @@id([product_id, menu_id])
}

In the menu update, I want to assign many products to the menu.

I've tried like this:

this.prisma.menu.update({where: {id}, data: {...updateMenuDto, products: {connect: {id: 6}}}});

but I received this error:

The required connected records were not found. Expected 1 records to be connected after connect operation on one-to-many relation 'MenuToMenuProducts', found 0.

Anyway, I've tried like this:

this.prisma.menuProducts.create({data:{menu: {connect: {id: id}},product: {connect: {id: 6}}}})

and it worked, but on the second call I saw what the line was duplicated. How I can link multiple products to menu without inserting duplicates?

CodePudding user response:

To remove duplicates from the MenuProducts model you can define a unique constraint on the combination of product_id and menu_id which will restrict having duplication of product and menu id.

model MenuProducts {
  menu_id Int
  menu Menu @relation(fields: [menu_id], references: [id])

  product_id Int
  product Product @relation(fields: [product_id], references: [id])


  created_at DateTime @default(now())
  updated_at DateTime @updatedAt

  @@map("menu_products")

  @@id([product_id, menu_id])

  @@unique([product_id, menu_id])
}

Here is a reference of @@unique constraint.

  • Related