如何 link Prisma 中的多对多项目而不重复

How to link many to many items in Prisma without duplicates

我在产品和菜单之间有多对多关系。

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])
}

在菜单更新中,我想将很多产品分配到菜单中。

我试过这样:

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

但是我收到了这个错误:

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

无论如何,我试过这样的:

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

它起作用了,但是在第二次调用时我看到了重复的行。如何在不插入重复项的情况下 link 将多个产品添加到菜单?

要从 MenuProducts 模型中删除重复项,您可以对 product_idmenu_id 的组合定义一个 unique 约束,这将限制产品和菜单的重复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])
}

这里是@@unique约束的引用。