use*_*932 3 graphql apollo-server prisma
尝试使用 Prisma 检查 Postgres 表中是否存在记录,但似乎我只能查询 id 字段,而不能查询任何其他字段,如name
和location
,这会产生编译器错误
模型schema.prisma
model place {
id Int @id @default(dbgenerated("nextval('place_id_seq'::regclass)"))
name String
location String @unique
}
Run Code Online (Sandbox Code Playgroud)
生成类型
export type Place = {
__typename?: 'Place';
name?: Maybe<Scalars['String']>;
location?: Maybe<Scalars['String']>;
};
Run Code Online (Sandbox Code Playgroud)
查询解析器
let findPlace = await prisma.place.findUnique(
{
where: {
name: "abc"
}
}
)
Run Code Online (Sandbox Code Playgroud)
错误
Type '{ name: string; }' is not assignable to type 'placeWhereUniqueInput'.
Object literal may only specify known properties, and 'name' does not exist in type 'placeWhereUniqueInput'.ts(2322)
index.d.ts(1361, 5): The expected type comes from property 'where' which is declared here on type '{ select?: placeSelect | null | undefined; include?: placeInclude | null | undefined; rejectOnNotFound?: RejectOnNotFound | undefined; where: placeWhereUniqueInput; }'
Run Code Online (Sandbox Code Playgroud)
为了让这项工作成功,这里缺少什么?
Tas*_*mam 12
Prisma 不会接受findUnique
条件仅包含非唯一字段(在本例中为名称)的查询。如果您只是需要查找符合条件的地点记录是否存在,则可以使用count
API。
let placeCount = await prisma.place.count(
{
where: {
name: "abc"
}
}
)
// placeCount == 0 implies does not exist
Run Code Online (Sandbox Code Playgroud)
findUnique
仅适用于独特的领域。您不应该使用count
其中任何一个,因为它不必要地遍历整个表。
更好的方法是使用findFirst
,它基本上是LIMIT 1
数据库上的 a ,因此数据库可以在第一次命中后停止搜索更多结果。
const exists = !!await prisma.place.findFirst(
{
where: {
name: "abc"
}
}
);
Run Code Online (Sandbox Code Playgroud)
我正在使用!!
将对象转换为布尔值。
归档时间: |
|
查看次数: |
14749 次 |
最近记录: |