我正在寻找一种方法来定义 Prisma select 语句,然后在多个地方使用它。例如:
const userSelect: Prisma.UserSelect = {
id: true,
name: true,
}
const user = await prisma.user.findUnique({
where: { id: 1 },
select: userSelect
})
const posts = await prisma.post.findMany({
where: { authorId: 1 },
select: {
id: true,
user: {
select: userSelect
}
}
})
但是,这无法正常工作。在查询中使用 userSelect
时,查询知道 userSelect
是预期类型 Prisma.UserSelect
,但他们不知道哪些字段具有实际上被选中了。这最终将 user
和 posts.user
都键入为 {}
。
另一种方法是像这样编写 userSelect
:
const userSelect = {
id: true,
name: true,
} as const;
在查询中有效并正确键入查询结果。但是,现在我在 userSelect
的定义中失去了类型安全和自动完成功能。
有人能想出一种解决方案,既能在查询选择属性、查询结果中正常工作,又能在选择对象的定义中实现类型安全吗?
最佳答案
Prisma 刚刚发布了一篇涵盖这个确切主题的文章。 https://www.prisma.io/blog/satisfies-operator-ur8ys8ccq7zb
引用文章:
One of the most common use cases for the satisfies operator with Prisma is to infer the return type of a specific query method like a findUnique — including only the selected fields of a model and its relations.
import { Prisma } from "@prisma/client";
// Create a strongly typed `PostSelect` object with `satisfies`
const postSelect = {
title: true,
createdAt: true,
author: {
name: true,
email: true,
},
} satisfies Prisma.PostSelect;
// Infer the resulting payload type
type MyPostPayload = Prisma.PostGetPayload<{ select: typeof postSelect }>;
// The result type is equivalent to `MyPostPayload | null`
const post = await prisma.post.findUnique({
where: { id: 3 },
select: postSelect,
});
https://stackoverflow.com/questions/74157774/