'How to create the correct relation in Prisma
I want to build a chat application.
I have two models, a user and a message.
Each message should have a reference to a receiver and a sender which both are of type user.
The user should contain a list of all messages where he is sender or receiver.
I tried multiple things but there are always errors like it's missing the opposite field.
model User {
id Int
name String
messages Message[]
}
model Message {
id Int
text String
sender User
receiver User
}
Solution 1:[1]
I would model it like this:
```prisma
model User {
id Int @id
name String
sentMessages Message[] @relation("sentMessages")
receivedMessages Message[] @relation("receivedMessages")
}
model Message {
id Int @id
text String
sender User @relation(name: "sentMessages", fields: [senderId], references: [id])
receiver User @relation(name: "receivedMessages", fields: [receiverId], references: [id])
senderId Int
receiverId Int
}
```
This disambiguates the two relationships to the User model so Prisma can understand which is which.
You can read more about that concept in their docs.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Austin Crim |
