Heya. I seem to have a problem with relations. It ...
# orm-help
k
Heya. I seem to have a problem with relations. It says I must reference a unique criteria in the related model, but I can't do that, since the field is not meant to be unique. This is the gist:
Copy code
model User {
    id        String   @id @default("")

    habits        UserToHabit[] @relation(name: "UserToHabit_User", fields: [id], references: [userId])
    partnerHabits UserToHabit[] @relation(name: "UserToHabit_Partner", fields: [id], references: [partnerId])
    league        League        @relation(fields: [leagueId], references: [id])
}

model UserToHabit {
    id        String   @id @default("")

    user      User    @relation(name: "UserToHabit_User", fields: [userId], references: [id])
    partner   User?   @relation(name: "UserToHabit_Partner", fields: [partnerId], references: [id])
    habit     Habit   @relation(fields: [habitId], references: [id])
    habitId   String
    userId    String
    partnerId String?

    @@unique([habitId, userId])
}
The relation from UserToHabit to User goes fine, as it goes from userId to id, but the other way around doesn't, as it goes from id to userId, but userId on UserToHabit isn't and can't be unique (habitId + userId is unique though). And I also can't remove the relation from User to UserToHabit because it doesn't let me.
r
@Kindly 👋 There’s an error with your schema. You don’t need to add references on the many side of the relation as that’s automatically implied. Your final schema would look like this:
Copy code
model User {
  id            String        @id @default("")
  habits        UserToHabit[] @relation(name: "UserToHabit_User")
  partnerHabits UserToHabit[] @relation(name: "UserToHabit_Partner")
}

model UserToHabit {
  id        String  @id @default("")
  user      User    @relation(name: "UserToHabit_User", fields: [userId], references: [id])
  partner   User?   @relation(name: "UserToHabit_Partner", fields: [partnerId], references: [id])
  userId    String
  partnerId String?
}
🙌 1
k
Thanks a lot! That made my day
🙌 1