0

我正在做一个附带项目,但遇到了一个我不知道如何解决的问题。我创建了两个模型,一个用于用户,一个用于项目。它们之间的关系是多对多的,因为很多用户可以有很多项目,但我也想在 Project 模型中添加 createdBy,这应该是一对一的,因为每个项目只能有一个用户谁创造了它。这就是我的模型的外观:

model User {
  id            String         @id @default(cuid())
  name          String?
  email         String?        @unique
  emailVerified DateTime?
  image         String?
  createdAt     DateTime       @default(now())
  updatedAt     DateTime       @updatedAt
  accounts      Account[]
  sessions      Session[]
  projects      Project[]
  Project       Project[]      @relation("userId")
}

model Project {
  id             Int          @id @default(autoincrement())
  createdAt      DateTime     @default(now())
  name           String
  favourite      Boolean      @default(false)
  archived       Boolean      @default(false)
  users          User[]
  about          String?
  archivedAt     String?
  deletedAt      String?
  createdBy      User         @relation("userId", fields: [userId], references: [id])
  userId         String
}

从 prisma migrate dev 得到的错误是

步骤 1 将所需列添加userIdProject表中,但没有默认值。此表有 2 行,无法执行此步骤。

不确定我做错了什么,因为我几乎是一个数据库建模新手。任何帮助,将不胜感激。

4

1 回答 1

3

为了实现你需要设置你的Many-to-Many文件,如:One-To-Manyschema.prisma

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  createdAt     DateTime  @default(now())
  updatedAt     DateTime  @updatedAt

  projects Project[]

  userProjects UserProjects[]
}

model Project {
  id         Int      @id @default(autoincrement())
  createdAt  DateTime @default(now())
  name       String
  favourite  Boolean  @default(false)
  archived   Boolean  @default(false)
  about      String?
  archivedAt String?
  deletedAt  String?

  createdBy User   @relation(fields: [user_id], references: [id])
  user_id   String

  projectUsers UserProjects[]
}

model UserProjects {
  project    Project @relation(fields: [project_id], references: [id])
  project_id Int
  user       User    @relation(fields: [user_id], references: [id])
  user_id    String

  @@id([project_id, user_id])
}

它应该成功迁移。

于 2021-07-21T04:49:24.080 回答