PrismaP
Prisma2y ago
1 reply
Chow why did

How to add a custom field on query result?

I have an implicit many-to-many relation: User and Post. A user could like many posts, and a post could be liked by many users.
Here is the schema:
model User {
  id         String    @id @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
  posts      Post[]    @relation("author")
  likes      Post[]    @relation("like")

  @@map("users")
}

model Post {
  id         String    @id @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
  author     User      @relation("author", fields: [author_id], references: [id])
  author_id  String    @db.Uuid
  comments   Comment[]
  likedBy    User[]    @relation("like")

  @@map("posts")
}

Now I want to get the post lists to render. For every post, there will be a heart showing if it's already liked by current user. How could I get a structure with type Post & { isLiked: boolean } ? It would be perfect if it could be done in one query.
Was this page helpful?