如何为 Prisma 选择属性输入变量

Spa*_*gus 4 typescript prisma

我\xe2\x80\x99m 寻找一种方法来定义 Prisma select 语句,然后在多个地方使用它。例如:

\n
const userSelect: Prisma.UserSelect = {\n    id: true,\n    name: true,\n}\n\nconst user = await prisma.user.findUnique({\n    where: { id: 1 },\n    select: userSelect\n})\n\nconst posts = await prisma.post.findMany({\n    where: { authorId: 1 },\n    select: {\n        id: true,\n        user: {\n            select: userSelect\n        }\n    }\n})\n
Run Code Online (Sandbox Code Playgroud)\n

但是,\xe2\x80\x99 无法正常工作。userSelect在查询中使用时,查询知道userSelect是预期的类型Prisma.UserSelect,但它们不知道实际选择了哪些字段。最终输入userposts.userto be {}

\n

另一种方法是userSelect这样写:

\n
const userSelect = {\n    id: true,\n    name: true,\n} as const;\n
Run Code Online (Sandbox Code Playgroud)\n

这适用于查询并正确键入查询结果。但是,现在我在 的定义中失去了类型安全和自动完成功能userSelect

\n

有人能想到一种可以在查询选择属性、查询结果中正常工作的解决方案,并且还可以在选择对象的定义中实现类型安全吗?

\n

Mat*_*tel 9

Prisma 刚刚发布了一篇涵盖该主题的文章。\n https://www.prisma.io/blog/satisfies-operator-ur8ys8ccq7zb

\n

引用文章中的话:

\n
\n

Prisma 的满足运算符最常见的用例之一是推断特定查询方法的返回类型,例如 findUnique \xe2\x80\x94,仅包括模型的选定字段及其\n关系。

\n
\n
import { Prisma } from "@prisma/client";\n\n// Create a strongly typed `PostSelect` object with `satisfies`\nconst postSelect = {\n  title: true,\n  createdAt: true,\n  author: {\n    name: true,\n    email: true,\n  },\n} satisfies Prisma.PostSelect;\n\n// Infer the resulting payload type\ntype MyPostPayload = Prisma.PostGetPayload<{ select: typeof postSelect }>;\n\n// The result type is equivalent to `MyPostPayload | null`\nconst post = await prisma.post.findUnique({\n  where: { id: 3 },\n  select: postSelect,\n});\n
Run Code Online (Sandbox Code Playgroud)\n