【问题标题】:Prisma schema - Create a relation field from multiple possible foreign keys (OR relation)Prisma 模式 - 从多个可能的外键(或关系)创建关系字段
【发布时间】:2020-07-30 06:42:11
【问题描述】:

如何在 prisma 模式中创建一个relation field,以 2 个可能的 relation scalar fields 为目标?

例如,在足球比赛中,假设我们有以下 2 个模型:

model Match {
    team1Id     Int
    team1       Team        @relation("team1", fields: [team1Id], references: [id])

    team2Id     Int
    team2       Team        @relation("team2", fields: [team2Id], references: [id])
}

model Team {
    id          Int         @default(autoincrement()) @id
    name        String
    matches     Match[]     @relation( /* What to put here ? */ ) // <----
}

Team.matches 关系字段定义中添加什么以允许Team.matchs 包含球队从任何一方进行的任何比赛,作为team1 或作为team2?

【问题讨论】:

    标签: prisma


    【解决方案1】:

    这在 Prisma 中是不可能的!我在我们的repo for technical specifications 中创建了一个问题,以考虑改进此问题的方法!


    解决方法

    使用 Prisma,您始终需要在每个关系的两侧都有一个关系字段。这意味着您需要在 Team 上有两个关系字段,一个代表球队“作为球队 1”参加的比赛,另一个代表“作为球队 2”参加的比赛。

    model Match {
      team1Id Int
      team1   Team @relation("team1", fields: [team1Id], references: [id])
      team2Id Int
      team2   Team @relation("team2", fields: [team2Id], references: [id])
      @@id([team1Id, team2Id])
    }
    
    model Team {
      id             Int     @default(autoincrement()) @id
      name           String
      matchesAsTeam1 Match[] @relation("team1")
      matchesAsTeam2 Match[] @relation("team2")
    }
    

    【讨论】:

    • 这不适用于 MongoDB。我需要对 MongoDB 进行任何特殊处理吗? id 字段类型对我来说是字符串。
    猜你喜欢
    • 2022-01-19
    • 2020-09-14
    • 2019-07-30
    • 2022-11-25
    • 2020-11-28
    • 2021-09-17
    • 2021-07-25
    • 2021-05-03
    相关资源
    最近更新 更多