# @giraphql/plugin-prisma 中文文档

规范地址：https://npmcn.com/package/%40giraphql/plugin-prisma/

版本：0\.14\.0
npm 元数据更新时间：2022-04-05T14:20:11.122Z
中文译文更新时间：2026-11-16T10:02:41.172Z
软件包许可：ISC

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40giraphql/plugin-prisma
原文对照：https://npmcn.com/package/%40giraphql/plugin-prisma/?lang=original
项目主页：https://github.com/hayes/giraphql#readme
源码仓库：https://github.com/hayes/giraphql

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：430 kB，147 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：@prisma/client \*，graphql \>=15\.1\.0，typescript \>4\.5\.2
- 首次发布：2021-07-30T23:28:55.533Z
- 最新版本发布：2021-12-15T05:36:12.148Z
- 近 30 天下载量：2240（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：42（近 12 个月 0 个）

## 中文简介

一个 GiraphQL 插件, 用于更高效地与棱镜结合

## 安装

```sh
npm install @giraphql/plugin-prisma
```

也可以使用：`pnpm add @giraphql/plugin-prisma`、`yarn add @giraphql/plugin-prisma`、`bun add @giraphql/plugin-prisma`

## README

# GiraphQL 的 Prisma 插件

此插件提供了与棱镜的更紧密的集成, 从而更容易定义以棱镜为基础的对象 类型,帮助解决关系查询。 中继插件的集成程序 使定义节点和连接简单高效.

## 免责声明者

这个插件是实验性的,将来会有一些突破性的改变. 不要用这个 插件, 除非您愿意在即将到来的版本中处理中断的更改 。 此插件可能 引入小版本的 BREAKING 更改,直到其主要版本被提升到 0以上.

这个插件不需要构建由棱镜模型支撑的图表, 我也不建议使用 除非您对它如何构建查询有确切的理解.

此插件将允许通过单个棱镜查询解决常见的查询( prisma 可能仍然) 将它变成多个 SQL 查询,并为 更复杂的询问和边缘案例。 尽管如此,图克的API是复杂的, 这很重要 了解您的API能够执行的询问.

此插件解决查询的方式在设计上是高效的,同时仍然是可预测的 很简单 试图自动生成查询的工具往往难以理解 和理由,所以这个插件试图通过提供查询使事情尽可能清晰 选项以解析器和加载用户代码来启动实际查询。 一般选择 仅包含 `include`s 对于嵌入式关系(连接字段提供更复杂的查询选项). 例外的是,我们提供一个默认解析器 关系可以处理查询 如果数据不是由父字段预装的话。 此解析器所用的查询是 并详细叙述如下.

通过这个简单的方法,我们得到了一个API,它很容易理解,但仍然提供很多 价值和功能.

## 示例

以下是一个使用此插件的 API 的简单例子 。 还有更彻底的 (b) 详细列出下文示例中所使用的方法和备选办法.

如果您正在寻找一个与 [中继插件](https://giraphql.com/plugins/relay),参见 [中继整合](https://npmcn.com/package/%40giraphql/plugin-prisma/#readme-relay-integration) 下节.

```typescript
builder.prismaObject('User', {
  include: {
    profile: true,
  },
  findUnique: (user) => ({ id: user.id }),
  fields: (t) => ({
    id: t.exposeID('id'),
    email: t.exposeString('email'),
    bio: t.string({
      resolve: (user) => user.profile.bio,
    }),
    posts: t.relation('posts', {
      args: {
        oldestFirst: t.arg.boolean(),
      },
      query: (args, context) => ({
        orderBy: {
          createdAt: args.oldestFirst ? 'asc' : 'desc',
        },
      }),
    }),
  }),
});

builder.prismaObject('Post', {
  findUnique: (post) => ({ id: post.id }),
  fields: (t) => ({
    id: t.exposeID('id'),
    title: t.exposeString('title'),
    author: t.relation('author'),
  }),
});

builder.queryType({
  fields: (t) => ({
    me: t.prismaField({
      type: 'User',
      resolve: async (query, root, args, ctx, info) =>
        prisma.user.findUnique({
          ...query,
          rejectOnNotFound: true,
          where: { id: ctx.userId },
        }),
    }),
  }),
});
```

有了这个计划,你就能用一个单棱镜 解决这样的问题 查询(这仍然会导致一些SQL查询的优化).

```graphql
query {
  me {
    email
    posts {
      title
      author {
        id
      }
    }
  }
}
```

查询像

```graphql
query {
  me {
    email
    posts {
      title
      author {
        id
      }
    }
    oldPosts: posts(oldestFirst: true) {
      title
      author {
        id
      }
    }
  }
}
```

{\\fn黑体\\fs22\\bord1\\shad0\\3aHBE\\4aH00\\fscx67\\fscy66\\2cHFFFFFF\\3cH808080}会发出两通呼吁 {\\fn黑体\\fs22\\bord1\\shad0\\3aHBE\\4aH00\\fscx67\\fscy66\\2cHFFFFFF\\3cH808080}解决一切问题 `oldPosts`,秒后为 解决里面的一切 `oldPosts`. Prisma只能在一次查询中解决每个关系, 所以,我们需要一个单独的 处理第二个 `posts` 关系。 这可能有点神奇,但 阅读以下文件后,应该可以预测,而且希望易于理解.

## 没有插件的 GiraphQL + Prisma

如果您只想了解插件, 请随意跳过此部分, 但理解如何 使用没有插件的棱镜可能对评价此插件是否适合您的使用有用 案例.

使用没有插件的棱镜相对直线 `builder.objectRef` 方法.

以棱镜为后盾的简单创建类型的方法看起来像是:

```typescript
import { Post, PrismaClient, User } from '@prisma/client';

const db = new PrismaClient();
const UserObject = builder.objectRef<User>('User');
const PostObject = builder.objectRef<Post>('Post');

UserObject.implement({
  fields: (t) => ({
    id: t.exposeID('id'),
    email: t.exposeString('email'),
    posts: t.field({
      type: [PostObject],
      resolve: (user) =>
        db.post.findMany({
          where: { authorId: user.id },
        }),
    }),
  }),
});

PostObject.implement({
  fields: (t) => ({
    id: t.exposeID('id'),
    title: t.exposeString('title'),
    author: t.field({
      type: UserObject,
      resolve: (post) =>
        db.user.findUnique({ rejectOnNotFound: true, where: { id: post.authorId } }),
    }),
  }),
});

builder.queryType({
  fields: (t) => ({
    me: t.field({
      type: UserObject,
      resolve: (root, args, ctx) =>
        db.user.findUnique({ rejectOnNotFound: true, where: { id: ctx.userId } }),
    }),
  }),
});
```

设置了用户, 以及带有几个字段的 Post 对象, 以及 a `me` 查询返回当前 用户。 在此设定中有一些需要注意的事情:

1.  我们分开 `builder.objectRef` 编辑 `implement` 电话,而不是电话 `builder.objectRef(...).implement(...)`。这可以防止打字机被 与用户之间的通知参考.
2.  我们用拒绝 与我们 `findUnique` 因为这些字段并非无效. 如果没有此选项, 棱镜会返回一个无效值, 如果找不到对象 。 另一种办法是 标记这些字段为无效.
3.  我们对象类型的参考文献叫做 `UserObject` 财务报告和审定财务报表 `PostObject`,这是因为 `User` 财务报告和审定财务报表 `Post` 是从棱镜导入的类型名称。 换句话说,当我们 导入它们, 这样我们就可以在模型之后为我们的 GraphQL 类型命名 .

这种设置相当简单,但很容易看到我们可能遇到的n+1问题. Prisma 帮助 但在执行过程中,我们还可以做一些事情 改进一切.

如果我们知道我们每次装上一个帖子 通常都会装上作者的话 我们可以做的就是 使作者成为某一职位所需的形状的一部分:

```typescript
const UserObject = builder.objectRef<User>('User');
// We add the author here in the objectRef
const PostObject = builder.objectRef<Post & { author: User }>('Post');

UserObject.implement({
  fields: (t) => ({
    id: t.exposeID('id'),
    email: t.exposeString('email'),
    posts: t.field({
      type: [PostObject],
      resolve: (user) =>
        db.post.findMany({
          // We now need to include the author when we query for posts
          include: {
            author: true,
          },
          where: { authorId: user.id },
        }),
    }),
  }),
});

PostObject.implement({
  fields: (t) => ({
    id: t.exposeID('id'),
    title: t.exposeString('title'),
    author: t.field({
      type: UserObject,
      // Now we can just return the author from the post instead of querying for it
      resolve: (post) => post.author,
    }),
  }),
});
```

不过我们可能并不总想找作者 这样我们就可以让作者任选而掉下去 返回到使用询问, 如果未由母解析器提供 :

```typescript
const PostObject = builder.objectRef<Post & { author?: User }>('Post');

PostObject.implement({
  fields: (t) => ({
    id: t.exposeID('id'),
    title: t.exposeString('title'),
    author: t.field({
      type: UserObject,
      resolve: (post) =>
        post.author ?? db.user.findUnique({ rejectOnNotFound: true, where: { id: post.authorId } }),
    }),
  }),
});
```

有了这个设置,一个家长解决者可以选择包括作者,但我们有一个倒计时 以防万一它没有.

还有其它模式,如数据加载器,不能用来减少 n+1 个问题,并制作您的图 更有效率,但它们太复杂,无法在这里描述.

## 使用量

### 安装

```bash
yarn add @giraphql/plugin-prisma
```

### 设置

这个插件需要比其他插件多一点的设置,因为它与棱镜融合到 生成一些类型,帮助插件更好地了解您的棱镜图案。 以往版本 这个插件曾经从棱镜客户端本身推断出所有需要的类型,但这导致了一个 复杂的类型使编辑工作减慢,一些更先进的使用案例 无法正确输入 .

#### 在您的棱镜图中添加一个 graphql 生成器

```
generator giraphql {
  provider = "prisma-giraphql-types"
}
```

当您重新生成您的棱镜客户端时, 将会生成 giraphql 使用的类型 。 运行 遵循命令重新生成客户端并创建新类型 :

```bash
npx prisma generate
```

其他选项:

-   `clientOutput`: 生成的代码将导入 PrismaClient 。 默认是 生成客户端的完整路径 。 如果您正在检查生成的文件, 使用 `@prisma/client` 是个好选择.
-   `output`: 在哪里写入生成的类型

有更多选项的示例:

```
generator giraphql {
  provider = "prisma-giraphql-types"
  clientOutput = "@prisma/client"
  output = "./giraphql-types.ts"
}
```

#### 设置建设者

```typescript
import SchemaBuilder from '@giraphql/core';
import { PrismaClient } from '@prisma/client';
import PrismaPlugin from '@giraphql/plugin-prisma';
// This is the default location for the generator, but this can be customized as described above
// Using a type only import will help avoid issues with undeclared exports in esm mode
import type PrismaTypes from '@giraphql/plugin-prisma/generated';

const prisma = new PrismaClient({});

const builder = new SchemaBuilder<{
  PrismaTypes: PrismaTypes;
}>({
  plugins: [PrismaPlugin],
  prisma: {
    client: prisma,
  },
});
```

强烈建议不要将您的棱镜客户端放入 `Context`。这将导致速度放慢 类型检查和在VSCode的拉吉开发者经验。 见 [https://github.com/microsoft/TypeScript/issues/45405 (中文(简体) )](https://github.com/microsoft/TypeScript/issues/45405) 更多细节.

### 创建一些类型 `builder.prismaObject`

`builder.prismaObject` 需要两个参数:

1.  `name`: 这个新类型的棱镜模型的名称代表
2.  `options`: 正在创建类型的选项, 这与其它选项非常相似 对象类型

```typescript
builder.prismaObject('User', {
  // Optional name for the object, defaults to the name of the prisma model
  name: 'PostAuthor',
  findUnique: null,
  fields: (t) => ({
    id: t.exposeID('id'),
    email: t.exposeString('email'),
  }),
});

builder.prismaObject('Post', {
  findUnique: null,
  fields: (t) => ({
    id: t.exposeID('id'),
    title: t.exposeString('title'),
  }),
});
```

目前,这只是创建一些简单的对象类型. 他们的工作就像其他的物体类型一样 (原始内容存档于2018-03-21). GiraphQL. 他们的主要优点是,我们得到的类型信息 不使用对象参考, 或需要从棱镜客户端进口.

这个 `findUnique` 选项将在下文中进一步说明.

### 在非主对象中添加棱镜字段( 包括查询和突变)

有一个新的 `t.prismaField` 用于定义解析棱镜的字段的方法 类型 :

```typescript
builder.queryType({
  fields: (t) => ({
    me: t.prismaField({
      type: 'User',
      resolve: async (query, root, args, ctx, info) =>
        prisma.user.findUnique({
          ...query,
          rejectOnNotFound: true,
          where: { id: ctx.userId },
        }),
    }),
  }),
});
```

这个方法很正常 `t.field` 方法,带有若干不同之处:

1.  这个 `type` 选项必须包含棱镜模型的名称(如:. `User` 或者说 `[User]` 列表 页:1.
2.  这个 `resolve` 函数有新的第一个参数 `query` 并扩展为查询棱镜 查询。 这将被用于加载嵌入关系的数据.

你不需要使用这种方法,而且 `builder.prismaObject` 方法返回对象比 可以像其他任何对象参考(与 `t.field`),但使用 `t.prismaField` 允许你 利用更有效的查询.

这个 `query` 对象将包含 `include` 对象,用于解析嵌入部分所需的预装数据 当前查询。 这是基于定义的字段 `t.relation` 说明如下.

如果没有使用字段 `t.relation` 在你的询问中,所有事情都会如愿以偿 没有此插件.

### 添加关系

您可以使用 `t.relation` 方法 :

```typescript
builder.prismaObject('User', {
  findUnique: null,
  fields: (t) => ({
    id: t.exposeID('id'),
    email: t.exposeString('email'),
    posts: t.relation('posts', {
      resolve: (query, user) =>
        db.post.findMany({
          ...query,
          where: { authorId: user.id },
        }),
    }),
  }),
});

builder.prismaObject('User', {
  findUnique: null,
  fields: (t) => ({
    id: t.exposeID('id'),
    title: t.exposeString('title'),
    author: t.relation('author', {
      resolve: (query, post) =>
        db.user.findUnique({ ...query, rejectOnNotFound: true, where: { id: post.authorId } }),
    }),
  }),
});
```

`t.relation` 定义可由父解析器预先加载的字段,并且大多数时间是 `resolve` 函数将不会调用。 这是非常重要的 要理解,因为它是 将不一致引入到您的 API 中的最大位置 。 这个 `resolve` 函数用于加载关系,如果父解析器没有预先加载所需的数据 解决领域。 出现这种情况有若干原因:

1.  父对象没有被装入定义的字段 `t.prismaField`,或 `t.relation`
2.  这个 `query` 用于母字段的对象没有被分散到查询中
3.  图表ql 查询要求依赖同一关系的多个字段(描述 (见下文)

这些都是好的, 和预期的情况。 Graphql API 非常灵活, 神奇地推动 对任意查询来说,将所有问题都输入一个单一查询是不可能的。 这就是为什么我们有一个 `resolve` 函数不能装入关系 IF 它没有被父程序装入.

喜欢 `t.prismaField`,则 `resolve` 函数现在作为一个新的第一个参数,即查询应该 被分散到查询中,用于加载嵌入式关系.

### 查找独有性

因为 `resolve` 函数仅用作倒置,测试难度更大,如果完成 错误地可能引入不一致。 虽然这不应该太难 正确,它可能是 最好彻底避免它。 要做到这一点,我们可以让 Prisma 插件生成这些决心 以一致和可预测的方式为您发挥功能。 我们可以提供独家的发现 选项。 定义a `findUnique` 这不是无效的,将制造 `resolve` 选项.

```typescript
builder.prismaObject('User', {
  findUnique: (user) => ({ id: user.id }),
  fields: (t) => ({
    id: t.exposeID('id'),
    email: t.exposeString('email'),
    posts: t.relation('posts'),
  }),
});

builder.prismaObject('Post', {
  findUnique: (post) => ({ id: post.id }),
  fields: (t) => ({
    id: t.exposeID('id'),
    title: t.exposeString('title'),
    author: t.relation('author'),
  }),
});
```

这大大简化了我们的物体类型。 在这些情况下,后退解决功能将 使用 `findUnique` 作为条款的位置,然后 `include` 页:1 关系。 这可以产生比手动略低效率的查询 执行, 因为主对象先被重新装入, 但会分批多个 关系到一个查询,发现独有查询应当非常快.

例如,如果 `User` 在没有预装的情况下加载,而且两者均 `posts` (单位:千美元) `profile` 关系 如果有要求,生成的棱镜呼吁将类似于:

```typescript
prisma.user.findUnique({
  rejectOnNotFound: true,
  where: { id: user.id },
  include: {
    posts: true,
    profile: true,
  },
});
```

### 筛选、排序和参数

到目前为止,我们一直在描述非常简单的询问, 没有任何论据、过滤或排序。 对于 `t.prismaField` 定义,您可以像正常一样将参数添加到字段,然后将它们传递到 您需要的棱镜查询。 对于 `t.relation` 流动有点不同,因为我们需要做 如果我们在母解析器中预装数据, 我们肯定正在装入正确的数据 。 我们这样做的方式 添加一个 `query` 选项.

```typescript
builder.prismaObject('User', {
  findUnique: (user) => ({ id: user.id }),
  fields: (t) => ({
    id: t.exposeID('id'),
    email: t.exposeString('email'),
    posts: t.relation('posts', {
      // We can define arguments like any other field
      args: {
        oldestFirst: t.arg.boolean(),
      },
      // Then we can generate our query conditions based on the arguments
      query: (args, context) => ({
        orderBy: {
          createdAt: args.oldestFirst ? 'asc' : 'desc',
        },
      }),
    }),
  }),
});
```

此查询将成为 `query` 被传入第一个论点 `resolve` 函数用于 `t.relation` 财务报告和审定财务报表 `t.prismaField` 并包含诸如 `where`, (中文(简体) ), `skip`, (中文(简体) ), `take`, (中文(简体) ), `orderBy`等 (中文(简体) ). 这个 `query` 函数将传递字段的参数,以及 当前请求的背景。 由于它被用于预装数据,以及解决n+1问题,所以 无法通过 `parent` 对象,因为它可能尚未被装入.

如果你的球场 `resolve` 生成方法 `query` 将作为第一部分 显示您的决心函数

```typescript
builder.prismaObject('User', {
  findUnique: null,
  fields: (t) => ({
    id: t.exposeID('id'),
    email: t.exposeString('email'),
    posts: t.relation('posts', {
      // We can define arguments like any other field
      args: {
        oldestFirst: t.arg.boolean(),
      },
      // Then we can generate our query conditions based on the arguments
      query: (args, context) => ({
        orderBy: {
          createdAt: args.oldestFirst ? 'asc' : 'desc',
        },
      }),
      // query here will contain the orderBy (and any other properties returned by the query method)
      resolve: (query, post) => db.post.findMany({ ...query, where: { id: post.authorId } }),
    }),
  }),
});
```

将所有过滤和排序放入查询方法,而不是你的 解析器,因为解析器只用作倒置,以及任何在 查询方法不会被正确应用 。 如果你的询问和你的 解析器, 您需要确保这些被正确合并 。 一般来说,最好不要使用 定制解析器.

### 包括类型

在某些情况下,您可能想要总是预装某些关系. 这有助于界定 字段,其中基础数据可能来自相关表格.

```typescript
builder.prismaObject('User', {
  // This will always include the profile when a user object is loaded.  Deeply nested relations can
  // also be included this way.
  include: {
    profile: true,
  },
  findUnique: (user) => ({ id: user.id }),
  fields: (t) => ({
    id: t.exposeID('id'),
    email: t.exposeString('email'),
    bio: t.string({
      // The profile relation will always be loaded, and user will now be typed to include the
      // profile field so you can return the bio from the nested profile relation.
      resolve: (user) => user.profile.bio,
    }),
  }),
});
```

### 关系

Prisma 支持查询 [关系计数](https://www.prisma.io/docs/concepts/components/prisma-client/aggregation-grouping-summarizing#count-relations) 包括彼此关系的理由 `includes`。目前没有 支持计数上的任何过滤器,但可以给出关系的总数.

```typescript
builder.prismaObject('User', {
  findUnique: (user) => ({ id: user.id }),
  fields: (t) => ({
    id: t.exposeID('id'),
    postCount: t.relationCount('posts'),
  }),
});
```

## 中继整合

此插件已广泛整合到 [中继插件](https://giraphql.com/plugins/relay), (中文(简体) ), 这使得建立节点和连接变得非常容易.

### 示例

下面的例子与上面的例子相似,有几处改动:

-   页:1 `User` 财务报告和审定财务报表 `Post` 对象现在是中继节点
-   页:1 `posts` 选项 `User` 类型现在是使用以光标为基础的 pagination 的中继连接
-   有一个新的 `users` 查询也是中继连接

这个计划中的每件事物仍然可以通过一个单棱镜查询. 中继连接 处理像所有其他字段一样的预装.

```typescript
builder.prismaNode('User', {
  findUnique: (id) => ({ id }),
  id: { resolve: (user) => user.id },
  fields: (t) => ({
    email: t.exposeString('email'),
    posts: t.relatedConnection('posts', {
      cursor: 'id',
      args: {
        oldestFirst: t.arg.boolean(),
      },
      query: (args, context) => ({
        orderBy: {
          createdAt: args.oldestFirst ? 'asc' : 'desc',
        },
      }),
    }),
  }),
});

builder.prismaNode('Post', {
  findUnique: (id) => ({ id }),
  id: { resolve: (post) => post.id },
  fields: (t) => ({
    title: t.exposeString('title'),
    author: t.relation('author'),
  }),
});

builder.queryType({
  fields: (t) => ({
    me: t.prismaField({
      type: 'User',
      resolve: async (query, root, args, ctx, info) =>
        prisma.user.findUnique({
          ...query,
          rejectOnNotFound: true,
          where: { id: ctx.userId },
        }),
    }),
    posts: t.prismaConnection({
      type: 'Post',
      cursor: 'id',
      resolve: (query) => prisma.post.findMany(query),
    }),
  }),
});
```

### `prismaNode`

这个 `prismaNode` 方法的工作原理与 `prismaObject` 数个小方法 差异 :

-   页:1 `findUnique` 函数现在只接收 ID。 用于支持中继装入节点的能力 由编号.
-   有一个新的 `id` 选项 `id` 选项从 `node` 中继插件的方法, 并必须包含一个解析函数,从节点实例中返回 id.

```typescript
builder.prismaNode('Post', {
  // This is used to load the node by id
  findUnique: (id) => ({ id }),
  // This is used to get the id from a node
  id: { resolve: (post) => post.id },
  // fields work just like they do for builder.prismaObject
  fields: (t) => ({
    title: t.exposeString('title'),
    author: t.relation('author'),
  }),
});
```

### `prismaConnection`

这个 `prismaConnection` 用于创建中继器的方法 `connection` 字段 也预装了连接内的所有数据.

```typescript
builder.queryType({
  fields: (t) => ({
    posts: t.prismaConnection(
      {
        type: 'Post',
        cursor: 'id',
        resolve: (query, parent, args, context, info) => prisma.post.findMany({ ...query }),
      }),
      {}, // optional options for the Connection type
      {}, // optional options for the Edge type),
    ),
  }),
});
```

#### 选项

-   `type`: 正在连接的棱镜模型的名称
-   `cursor`(单位:千美元) `@unique` 正连接到该模型的列。 这是用来作为 `cursor` 选项 传到棱镜.
-   `defaultSize`: (默认: 20) 如果 `first` 财务报告和审定财务报表 `last` 未提供.
-   `maxSize`: (默认: 100) 连接的最大节点数返回 .
-   `resolve`: 像解决器 `prismaField`第一个论点是 `query` 对象 扩展到您的棱镜查询中。 这个 `resolve` 函数应返回该函数的节点数组 连接。 这个 `query` 将包含正确的 `take`, (中文(简体) ), `skip`,以及 `cursor` 选项 连接参数( e)`before`, (中文(简体) ), `after`, (中文(简体) ), `first`, (中文(简体) ), `last`报告 `include` 嵌入式选项 选择.

创建的连接查询目前支持以下连接参数的组合:

-   `first`, (中文(简体) ), `last`,或 `before`
-   `first` 财务报告和审定财务报表 `before`
-   `last` 财务报告和审定财务报表 `after`

其他组合的查询没有那么有用,通常需要装入所有记录 在2个光标之间,或在光标和集尾之间。 生成这些查询选项 案件更为复杂,而且可能效率极低,因此目前它们会投出错误 参数组合不支持.

### `relatedConnection`

这个 `relatedConnection` 用于创建中继器的方法 `connection` 基于关系的字段 ,当前模式.

```typescript
builder.prismaNode('User', {
  findUnique: (id) => ({ id }),
  id: { resolve: (user) => user.id },
  fields: (t) => ({
    // Connections can be very simple to define
    simplePosts: t.relatedConnection('posts', {
      cursor: 'id',
    }),
    // Or they can include custom arguments, and other options
    posts: t.relatedConnection(
      'posts',
      {
        cursor: 'id',
        args: {
          oldestFirst: t.arg.boolean(),
        },
        query: (args, context) => ({
          orderBy: {
            createdAt: args.oldestFirst ? 'asc' : 'desc',
          },
        }),
      },
      {}, // optional options for the Connection type
      {}, // optional options for the Edge type),
    ),
  }),
});
```

#### 选项

-   `cursor`(单位:千美元) `@unique` 正连接到该模型的列。 这是用来作为 `cursor` 选项 传到棱镜.
-   `defaultSize`: (默认: 20) 如果 `first` 财务报告和审定财务报表 `last` 未提供.
-   `maxSize`: (默认: 100) 连接的最大节点数返回 .
-   `resolve`: (可选)当连接没有被预装时用作倒置. 这是可选的,和 一般不应手工定义。 如果使用它的工作 就像组合 `resolve` 方法 `relation` 财务报告和审定财务报表 `prismaConnection`默认将使用 `findUnique` 当前 型号,带有 `include` 用于当前关系。 也与其他产品一起分批处理 提高查询效率的关系.
-   `totalCount`: 当设置为真时, 这将添加一个 `totalCount` 字段到连接对象。 见 `relationCount` 详见上文.

## 常见问题

### @giraphql/plugin-prisma 是什么？

一个 GiraphQL 插件, 用于更高效地与棱镜结合

### 如何安装 @giraphql/plugin-prisma？

在项目目录运行 npm install @giraphql/plugin-prisma，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@prisma/client（\*）、graphql（\>=15\.1\.0）、typescript（\>4\.5\.2）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。它还提供命令行工具 prisma-giraphql-types，可以用 npx prisma-giraphql-types 直接运行。

### @giraphql/plugin-prisma 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @giraphql/plugin-prisma 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @giraphql/plugin-prisma 可以商用吗？

@giraphql/plugin-prisma 使用 ISC 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @giraphql/plugin-prisma 的下载量有多少？

根据 npm 官方下载统计，@giraphql/plugin-prisma 在 2026/10/17 – 2026/11/15 这 30 天内被下载 2,240 次，日均约 75 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @giraphql/plugin-prisma 还在维护吗？

最新版本 0\.14\.0 发布于 2021/12/15（4 年前）；至今共发布 42 个版本，其中过去 12 个月发布了 0 个；首次发布于 2021/07/31。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

