基于关系结果计数的GraphQL过滤/排序

问题描述 投票:0回答:1

我对 GraphQL 世界有点陌生,我想说,我陷入了一个非常基本的问题。我翻阅了几个文档和指南,但我找不到任何提示是否可以使用 GraphQL 或可能的解决方法。

我想要实现的是一个简单的查询,来自在各种指南上找到的known示例(帖子/作者):

get all authors with more than one post
或至少
get all authors sorted by their count of posts

这是从浏览器使用 GraphQL 的角度来看的。我知道它可能还取决于 GraphQL 服务器实现,我正在使用 Prisma。但也提示了任何值得赞赏的服务器解决方案的解决方案。

经过相当多的挖掘,我没有发现任何提示是否可能发生这样的事情,甚至从哪里开始。我想知道这是否是一个特殊的用例,以至于我发现的任何指南中都没有提到它。坦白说,我不知道如何解决这个问题。有可能吗?如果不是,解决方法可能是什么?查询后的过滤可能不起作用,因为当然会想到有数千名作者的场景,其中分页和性能可能会崩溃。

model User {
  id                          String              @id @default(cuid())
  name                        String              @default("")
  email                       String              @unique @default("")
  password                    String
  posts                       Post[]              @relation("Post_author")
  createdAt                   DateTime?           @default(now())
}

model Post {
  id       String  @id @default(cuid())
  title    String  @default("")
  content  Json    @default("[{\"type\":\"paragraph\",\"children\":[{\"text\":\"\"}]}]")
  author   User?   @relation("Post_author", fields: [authorId], references: [id])
  authorId String? @map("author")
  tags     Tag[]   @relation("Post_tags")

  @@index([authorId])
}

任何帮助表示赞赏。

graphql prisma apollo-client
1个回答
0
投票

文档的重要部分位于此处:https://www.prisma.io/docs/orm/prisma-client/queries/aggregation-grouping-summarizing#return-a-relations-count-with-include

我最终编写了这样的查询:

   await prisma.User.findMany({
        take: PAGE_SIZE,
        skip: PAGE_SIZE * (pageNum - 1),
        orderBy: {
            posts: {
              _count: 'desc',
            },
        },
        where: {
            posts: {
                some: {
                    status: 'active',
                }
            },
        },
        include: {
            _count: {
                select: {
                    posts: {
                        where: { status: 'active' },
                    }
                }
            }
        },
    });

重要的部分是

include
指令,其中包含查询结果中的计数。我还根据此处发布
'active'
帖子的所有用户添加了排序和自定义过滤器。

© www.soinside.com 2019 - 2024. All rights reserved.