You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取包含关联关系的Prisma模型TypeScript类型?

获取Prisma关联查询结果的TypeScript类型

当你用Prisma查询包含关联的模型时,默认生成的Event类型只包含基础字段,不会带上关联属性。下面是两种靠谱的解决方法:

方法一:用Prisma内置的GetPayload工具类型

Prisma提供了Prisma.ModelNameGetPayload工具类型,可以根据你的查询配置生成对应的结果类型。比如你查询Event时要包含Owner关联,写法如下:

import { Prisma } from "@prisma/client";

// 直接定义包含Owner的查询配置,并生成对应的结果类型
type EventWithOwner = Prisma.EventGetPayload<{
  include: { Owner: true };
}>;

// 在组件Props中使用这个类型
type EventDetailsProps = {
  event: EventWithOwner;
};

如果你的关联配置更复杂(比如嵌套多层关联),也可以直接在include里写完整的结构,GetPayload会自动生成对应的嵌套类型。

方法二:从查询函数返回值推断类型

如果已经有现成的查询函数,可以直接从函数的返回值里提取类型,不用手动写配置:

import { prisma } from "../your-prisma-client-path";

// 定义查询函数
async function fetchEventWithOwner(eventId: string) {
  return prisma.event.findUnique({
    where: { id: eventId },
    include: { Owner: true },
  });
}

// 提取函数返回值的类型(Awaited用来处理Promise)
type EventWithOwner = Awaited<ReturnType<typeof fetchEventWithOwner>>;

// 组件Props类型
type EventDetailsProps = {
  event: EventWithOwner;
};

为什么之前的写法不生效?

  • 默认的Event类型是Prisma生成的基础模型类型,只包含表本身的字段,不会包含任何关联数据。
  • Prisma.EventInclude是用来配置查询时要包含哪些关联的类型,不是查询结果的类型,所以不能直接用来定义组件Props。

内容的提问来源于stack exchange,提问作者Gerrit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 05:12:37