【问题标题】:Prisma 1:1 relation with no optional field on MySQL?MySQL 上没有可选字段的 Prisma 1:1 关系?
【发布时间】:2022-12-22 02:05:53
【问题描述】:

我正在查看 Prisma 的 1:1 关系文档,我看到了这段代码:

  id      Int      @id @default(autoincrement())
  profile Profile?
}

model Profile {
  id     Int  @id @default(autoincrement())
  user   User @relation(fields: [userId], references: [id])
  userId Int  @unique // relation scalar field (used in the `@relation` attribute above)
}

它说一个用户可以有 0 或 1 个配置文件。但是如果我想确保用户必须有个人资料怎么办?

【问题讨论】:

    标签: prisma


    【解决方案1】:

    您可以选择带有关系标量的关系的一侧是可选的还是强制的。在以下示例中,profile 和 profileId 是必需的。这意味着您无法在不连接或创建配置文件的情况下创建用户

    model User {
      id        Int     @id @default(autoincrement())
      profile   Profile @relation(fields: [profileId], references: [id]) // references `id` of `Profile`
      profileId Int     @unique // relation scalar field (used in the `@relation` attribute above)
    }
    
    model Profile {
      id   Int   @id @default(autoincrement())
      user User
    }
    

    有关必需和可选的 1-1 关系,请参阅文档的此section

    【讨论】:

    • 但是那个“?”意味着我可以在没有用户权限的情况下创建配置文件?有没有办法不允许创建没有配置文件的用户和没有用户的配置文件?
    • 在那种情况下,您将省略 ?在用户关系中
    猜你喜欢
    • 2021-02-20
    • 2016-12-24
    • 2011-08-26
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 2014-04-12
    相关资源
    最近更新 更多