Daniel Hoops
Daniel Hoops

Reputation: 59

How can I leverage Prisma's implicit relations to create the following relation? (one-many, many-many, one-one)

I'm learning Prisma,

I want to leverage Prisma's Implicit relations as much as possible for the following relation (and later I want to use nexus for writing queries):

enter image description here

So far I have come up with this (but I highly doubt it's correct because its not behaving as I want it to when using with nexus):

model User {
  id            String         @id @default(uuid())
  conversations Conversation[]
}

model Message {
  id        String   @id @default(uuid())
  authorId       String
  conversationId String
  author         User         @relation(fields: [authorId], references: [id])
  conversation   Conversation @relation(fields: [conversationId], references: [id])
}

model Conversation {
  id        String   @id @default(uuid())
  participants User[]
  messages     Message[]
}

Could I please get some pointers/help to proceed?

Upvotes: 2

Views: 346

Answers (2)

Daniel Olavio Ferreira
Daniel Olavio Ferreira

Reputation: 520

I believe this schema would solve it to you. If you want to know more, I gave a talk about this topic a while back.

model User {
  id            String         @id @default(uuid())
  messages      Message[]
  conversations Conversation[]
}

model Message {
  id             String       @id @default(uuid())
  author         User         @relation(fields: [authorId], references: [id])
  authorId       String
  conversation   Conversation @relation(fields: [conversationId], references: [id])
  conversationId String
}

model Conversation {
  id       String    @id @default(uuid())
  messages Message[]
  members  User[]
}

Upvotes: 1

Victor Iris
Victor Iris

Reputation: 323

following your requirements list this schema is pretty much ready. Just add the messages field on the User model to declare its side of the relationship.

It would be like this:

model User {
  id            String         @id @default(uuid())
  conversations Conversation[]
  messages      Message[]
}

model Message {
  id             String       @id @default(uuid())
  authorId       String
  conversationId String
  author         User         @relation(fields: [authorId], references: [id])
  conversation   Conversation @relation(fields: [conversationId], references: [id])
}

model Conversation {
  id           String    @id @default(uuid())
  participants User[]
  messages     Message[]
}

Do you have any specific issues that occur when using Nexus with it?

I have a video tutorial that might help you with some extra guidance: https://www.youtube.com/watch?v=sWlzqRB5Xro

Upvotes: 1

Related Questions