Multiple relations between models

69 views Asked by At

I am struggling to understand how to build multiple relations between two models. Take the following:

model User {
  id             Int       @default(autoincrement()) @id
  goalBoard      GoalBoard[]
  ...
}

model GoalBoard {
  id          Int         @default(autoincrement()) @id
  goalOwner   User        @relation(fields: [goalOwnerId], references: [id])
  goalOwnerId Int
  invitee     User[]      @relation(name: "invitee") //?
  invited     User[]      @relation(name: "invited") //?
  ...
  @@unique([goalOwnerId, active])
}

The 'invitee' & 'invited' fields will have multiple users within them. I am not clear on the need / requirement for the adding a name to the @relation.

So, for understanding sake, what is the purpose behind naming the @relation. And secondly, how would I build the relation as per my requirement above.

Thank you.

1

There are 1 answers

3
Ahmed Elywa On BEST ANSWER

Here are the right and clear way to do your multiple many to many relations

enter image description here

model User {
  id               Int         @default(autoincrement()) @id
  goalBoardInvitee GoalBoard[] @relation(name: "UserGoalBoardInvitee")
  goalBoardInvited GoalBoard[] @relation(name: "UserGoalBoardInvited")
  ...
}

model GoalBoard {
  id          Int         @default(autoincrement()) @id
  goalOwner   User        @relation(fields: [goalOwnerId], references: [id])
  goalOwnerId Int
  invitee     User[]      @relation(name: "UserGoalBoardInvitee") //?
  invited     User[]      @relation(name: "UserGoalBoardInvited") //?
  ...
  @@unique([goalOwnerId, active])
}

To understand why we do this, please read the Prisma relations docs