简体   繁体   中英

Prisma js return join fields

I'm trying to implement batching and caching with the Facebook DataLoader . Let's say I have the following schema (taken from here ):

type Post {
  id: ID! @id
  title: String!
  published: Boolean! @default(value: false)
  author: User
  comments: [Comment!]!
}

type User {
  id: ID! @id
  name: String
  posts: [Post!]!
  comments: [Comment!]!
}

type Comment {
  id: ID! @id
  text: String!
  post: Post!
  writtenBy: User!
}

I am working on a tricky resolver which lists all comments created by the same user under the same post for a given comment. To retrieve a single entry I would go like:

const fetchCommentsByUserForSamePost = async (commentId: string, userId: string): Promise<Comment[]> => {
  const comments = await this.prisma.comment.findOne({ where: { id: commentId } })
    .post()
    .comments({
      where: {
        writtenBy: { id: userId }
      }
    })
  return comments;
}

This works well for a single query, but I would like to batch the queries. In raw SQL I'd return commentId and userId in every row, such that I can group the results by these fields. But I can't find a way to return the original commentId with Prisma to generalize the query to work with a list of commentId - userId pairs.

Is there a way to accomplish this with Prisma, or I am missing something? I am aware that making two requests could solve this, but that would result in an involved logic, plus I'd rather avoid making two DB roundtrips.

Prisma 2.0 already has a Dataloader built in exactly for this purpose. This means your resolvers might do multiple calls to findOne but those will be batched into one big SQL query under the hood. So there should be no need for you to implement this optimization on your own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM