Prisma JS返回联接字段

问题描述

我正在尝试使用Facebook DataLoader实现批处理和缓存。假设我有以下模式(取自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!
}

我正在开发一个棘手的解析器,该解析器列出了由同一用户在同一帖子下针对给定评论创建的所有评论。要检索单个条目,我会这样:

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;
}

这对于单个查询来说效果很好,但是我想对查询进行批处理。在原始sql中,我将在每一行中返回commentIduserId,以便可以按这些字段将结果分组。但是我找不到用prisma返回原始commentId方法来使查询泛化成commentId-userId对列表的工作方式。

是否可以通过prisma完成此操作,或者我缺少某些东西?我知道发出两个请求可以解决此问题,但是这会导致涉及逻辑,而且我宁愿避免进行两次数据库往返。

解决方法

Prisma 2.0已经专门为此目的内置了一个Dataloader。这意味着您的解析器可能会对findOne进行多次调用,但这些调用将在后台被批量处理为一个大型SQL查询。因此,您无需自己进行此优化。