Steven2105
Steven2105

Reputation: 550

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
}

Upvotes: 3

Views: 1405

Answers (1)

Austin Crim
Austin Crim

Reputation: 1267

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.

Upvotes: 5

Related Questions