简体   繁体   English

具有唯一一对多的 Prisma 模型

[英]Prisma Model with unique one to many

A Product can have various sizes so I added one to many relation.一个产品可以有不同的尺寸,所以我添加了一对多的关系。 But Each product can have only 1 unique size, ie, in many to many the sizes should not repeat.但是每个产品只能有 1 个唯一尺寸,即在多对多尺寸中不应重复。 For instance, Product X can have size 1, 2, 3 but if user tries to add size 2 which already exists, it should fail (and it does) but now the issue is when Product Y is added, adding size 1 fails because it was unique but It should be unique per variant not overall.例如,产品 X 可以有尺寸 1、2、3,但如果用户尝试添加已经存在的尺寸 2,它应该会失败(确实如此),但现在问题是在添加产品 Y 时,添加尺寸 1 失败,因为它是独一无二的,但每个变体应该是独一无二的,而不是整体。 Any way to do this while modelling the DB or I have to add a manual check and throw error if the size of the same variant already exists.在对数据库建模时执行此操作的任何方法,或者如果相同变体的大小已经存在,我必须添加手动检查并抛出错误。

Database - Postgresql Using Prisma数据库 - 使用 Prisma 的 Postgresql

You can create unique indexes using multiple fields in postgres.您可以在 postgres 中使用多个字段创建唯一索引。 https://www.postgresqltutorial.com/postgresql-indexes/postgresql-unique-index/ scroll down a bit for the multiple fields section. https://www.postgresqltutorial.com/postgresql-indexes/postgresql-unique-index/向下滚动多字段部分。

Without knowing your existing table structure I can't say with confidence that this code would work but you'll want something like this.在不知道您现有的表结构的情况下,我不能自信地说这段代码会起作用,但您会想要这样的东西。

CREATE UNIQUE INDEX idx_products_size ON products(id, size);

In Prisma, you can model your relations like this:在 Prisma 中,您可以像这样对关系建模:

model Product {
  id          String        @id @default(uuid())
  name        String
  description String
  sizes       ProductSize[]
}

model ProductSize {
  id          String  @id @default(uuid())
  name        String
  description String
  product     Product @relation(fields: [productId], references: [id])
  productId   String

  @@unique([productId, name])
}

This contains a unique index over a combination of two fields (productId and name).这包含两个字段(productId 和名称)组合的唯一索引。 So for each product there can only be a unique named size.因此,对于每个产品,只能有一个唯一的命名尺寸。 Example - (productId - A, Size - 1), (productId - A, Size - 2).示例 - (productId - A, Size - 1), (productId - A, Size - 2)。 Adding another record with (productId - A, Size - 1) would throw an error but (productId - B, Size - 1) will be allowed.使用 (productId - A, Size - 1) 添加另一条记录会引发错误,但 (productId - B, Size - 1) 将被允许。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM