PrismaP
Prisma2y ago
7 replies
Sky✧

Implicite Many-to-Many relationship double primary key

Implicite Many-to-Many relationship with two models, but one of these two models has a double primary key?
Solution
Here is an example of how you can define an explicit many-to-many relation based off of your example
model Kit {
  kitid            Int       @id @default(autoincrement())
  kitname          String
  guildid          BigInt
  guild            Guild     @relation(fields: [guildid], references: [guildid])
  channelid        BigInt?
  enable           Boolean   @default(false)
  kitrows          KitRow[]
  adminroles       KitRole[] @relation(name: "adminrole")
  requiredroles    KitRole[] @relation(name: "requiredrole")

  @@unique([kitname, guildid])
}

model Role {
  roleid           BigInt    
  guildid          BigInt 
  guild            Guild     @relation(fields: [guildid], references: [guildid])
  kitroles         KitRole[]

  @@id([roleid, guildid])
}

model KitRole {
  kitid            Int
  roleid           BigInt
  guildid          BigInt
  kit              Kit        @relation(fields: [kitid], references: [kitid])
  role             Role       @relation(fields: [roleid, guildid], references: [roleid, guildid])

  @@id([kitid, roleid, guildid])
}

In this schema, KitRole acts as the relation table between Kit and Role. The @@id([kitid, roleid, guildid]) in KitRole ensures that the combination of kitid, roleid, and guildid is unique. This allows you to store additional fields on the relation if needed and properly handles the composite primary key in the Role model.
Was this page helpful?