Home > database >  Prisma: What would be the best way to create relationships between 3 tables?
Prisma: What would be the best way to create relationships between 3 tables?

Time:09-29

I have the following models.How can I create a relationship for these tables so that I can get the roles associated with group and group associated with roles.One group will have multiple roles. Groups and Roles will be added separately though.Only after the Group is added can the roles be associated with them

model groups {
  id          Int      @id @default(autoincrement())
  group_name  String?  @unique
}

model roles {
  id          Int      @id @default(autoincrement())
  role_name   String?  @unique
}

model group_role_association {
  id          Int      @id @default(autoincrement())
  group_id    Int
  role_id     Int
}

CodePudding user response:

This seems like a use case for an implicit relation. This is a feature of Prisma that allows you to model a m-n relatinshiop between to tables without managing a relation table (in your example, I read group_role_association to be a relation table rather than an actual "model")?

model groups {
  id         Int        @id @default(autoincrement())
  groups_name  String
  roles      roles[]
}

model roles {
  id          Int    @id @default(autoincrement())
  role_name String
  groups    groups[]
}

Also, I'd actually recommend you to use Prisma's naming conventions (i.e. spell model names in singular form and PascalCase notation):

model Group {
  id    Int        @id @default(autoincrement())
  name  String
  roles Role[]
}

model Role {
  id     Int    @id @default(autoincrement())
  name   String
  groups Group[]
}
  • Related