Prisma - How to point two fields to same model?

Viewed 523

I'm having trouble conceptualizing how to handle this issue. I've pored through the Prisma docs and other SO questions, but they all seem to be slightly different from this situation.

I have two models:

model User {
  id                Int               @id @default(autoincrement())
  firstName         String?           @map("first_name")
  lastName          String?           @map("last_name")
  email             String            @unique
  password          String
  role              UserRole          @default(value: USER)
  image             String?           @map("image")
  createdAt         DateTime          @default(now()) @map("created_at")
  updatedAt         DateTime          @updatedAt @map("updated_at")

  friends       Friend[]

  @@map("users")
}

model Friend {
  id               Int      @id @default(autoincrement())
  inviteSentOn     DateTime @map("invite_sent_on") @db.Timestamptz(1)
  inviteAcceptedOn DateTime @map("invite_accepted_on") @db.Timestamptz(1)
  userId           Int      @map("user_id")
  friendId         Int      @map("friend_id")
  createdAt        DateTime @default(now()) @map("created_at")
  updatedAt        DateTime @updatedAt @map("updated_at")

  user User @relation(fields: [userId], references: [id])
  // friend User? @relation(name: "FriendFriend", fields: [friendId], references: [id])

  @@map("friends")
}

I want to be able to set up the relationships on the Friend model to both point towards the User model, however I receive errors such as Error validating field 'friend' in model 'Friend': The relation field 'friend' on Model 'Friend' is missing an opposite relation field on the model 'User'.

I've tried adding the name property to the @relation field, but start receiving errors about ambiguous relations being detected.

How do I go about setting these relations up correctly?

1 Answers

You just need to provide name to disambiguate relation, like that:

model User {
  id Int @id @default(autoincrement())
  friend Friend? 
  friends Friend[] @relation(name: "friends")
}

model Friend {
  id       Int @id @default(autoincrement())
  userId   Int
  friendId Int
  user User @relation(fields: [userId], references: [id])
  friend User @relation(fields: [friendId], references: [id], name: "friends")
}

And dont forget that both sides of relations need to have connections to the other.

Related