Prisma中查询多对多关系

SPi*_*SPi 1 prisma prisma-graphql

我想在 prisma 中查询多对多关系,例如“选择类别 ID 等于 'abc...' 的所有帖子”。

这看起来相当简单,但即使花了 2 小时阅读有关关系查询的 Prisma 文档,我也无法弄清楚。

model Category {
  id               String    @id @default(cuid())
  name             String
  post             Post[]
}

model Post {
  id               String    @id @default(cuid())
  body             String
  category         Category[]
}
Run Code Online (Sandbox Code Playgroud)
const posts = await prisma.post.findMany({
      select: { 
        category: {
          where: {id: "abc123"}
        }},
    });
Run Code Online (Sandbox Code Playgroud)

这将返回一个包含与帖子数量一样多的类别对象的数组。

Iro*_*ife 5

这将返回所有具有 id 类别的帖子abc123。请注意,帖子可能包含 id 以外的类别abc123

const posts = await prisma.post.findMany({
    where: {
        category: {
            some: {
                id: 'abc123',
            },
        },
    },
});
Run Code Online (Sandbox Code Playgroud)

some:返回一个或多个(“某些”)相关记录符合过滤条件的所有记录。

https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#some