使用带有嵌套包含的查询时,我无法从函数返回正确的类型。嵌套字段丢失。我使用与此类似的模型:
model Foo {
id String @id @default(cuid())
bar Bar[]
}
model Bar {
id String @id @default(cuid())
foo Foo @relation(fields: [fooId], references: [id], onDelete: Cascade, onUpdate: Cascade)
fooId String
baz Baz[]
}
model Baz {
id String @id @default(cuid())
bar Bar @relation(fields: [barId], references: [id], onDelete: Cascade, onUpdate: Cascade)
barId String
}
在本例中,
foo
的类型包含['bar'][number]['baz']
:
async function getFooById(id: Foo['id']) {
return prisma.foo.findUnique({
where: { id },
include: { bar: { include: { baz: true } } },
})
}
const foo = await getFooById('123')
if (foo !== null) {
const baz = foo.bar[0].baz
}
如果我尝试参数化包含(我可能输入错误),它就会停止工作:
import type { DefaultArgs } from '@prisma/client/runtime/library.js'
async function getFooById(
id: Foo['id'],
// this line is probably the cause for the error?
{ include }: { include: Prisma.FooInclude<DefaultArgs> } = { include: {} },
) {
return prisma.foo.findUnique({
where: { id },
include,
})
}
const foo = await getFooById('123', include: { bar: { include: { baz: true } } })
if (foo !== null) {
// error: baz is not defined on foo.bar[0]
const baz = foo.bar[0].baz
}
我觉得我需要指定不同的参数类型,或者可能根据参数显式派生返回类型 - 但如何?
另一种变体也不起作用,在结果返回类型中包含
baz
:
async function getFooById<ExtArgs extends Types.Extensions.InternalArgs = Types.Extensions.DefaultArgs>(
id: Foo['id'],
{ include }: { include: Prisma.FooInclude<ExtArgs> } = { include: {} },
) {
// …
}
使用的Prisma版本是5.8.0,Typescript是5.3.3。
我也面临同样的问题。目前我正在手动返回这些情况的类型。请告诉我是否有更好的解决方案。 🙇u200d♂️:
type FooWithBarsAndBazs = {
id: string;
bars: BarWithBazs[];
};
type BarWithBazs = Bar & { bazs: Baz[] };
async function getFooById(id: Foo['id']): Promise<FooWithBarsAndBazs> {
return prisma.foo.findUnique({
where: { id },
include: { bar: { include: { baz: true } } },
})
}
这是关于 prisma 如何调整其返回类型的文章。