如何 select 自定义用户模型 属性?
How to select a custom User model property?
我在 prisma.schema 文件中的用户模型中添加了一家公司 属性(prisma.schema 文件的其余部分仍然与文档中的相似:https://next-auth.js.org/adapters/prisma)
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
accounts Account[]
sessions Session[]
company Company?
}
model Company {
id Int @id @default(autoincrement())
companyName String @unique
gender String
firstName String
lastName String
street String
houseNumber Int
postcode Int
city String
country String
countryCode String
callNumber Int
emailAddress String
website String?
socials Json?
companyUser User @relation(fields: [companyUserId], references: [id])
companyUserId String @unique
}
整个身份验证过程即使在更改后也能正常工作,但是当我尝试从数据库中 select 一个用户时,它只 returns 用户的特定部分,即 id、名称、电子邮件、电子邮件验证和图像 属性。
我怎样才能改变这种行为?
const user = await prisma.user.findUnique({
where: {
id: ...
}
})
当然我只能创建 Company 模型而不将它连接到 User 模型并且可能将用户的 id 添加到它以具有隐式连接,但这破坏了整个目的...
你正在寻找 nested reads,如果你想包括整个 company
模型你应该使用 include
和关系的名称,注意这将 return 该特定关系的所有字段:
const user = await prisma.user.findUnique({
where: {
id: ...
},
include: {
company: true,
},
})
如果你想 return 特定关系字段与整个 user
你应该在 include
:
中使用 select
const user = await prisma.user.findUnique({
where: {
id: ...
},
include: {
company: {
select : {
firstName: true,
},
},
},
})
我在 prisma.schema 文件中的用户模型中添加了一家公司 属性(prisma.schema 文件的其余部分仍然与文档中的相似:https://next-auth.js.org/adapters/prisma)
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
accounts Account[]
sessions Session[]
company Company?
}
model Company {
id Int @id @default(autoincrement())
companyName String @unique
gender String
firstName String
lastName String
street String
houseNumber Int
postcode Int
city String
country String
countryCode String
callNumber Int
emailAddress String
website String?
socials Json?
companyUser User @relation(fields: [companyUserId], references: [id])
companyUserId String @unique
}
整个身份验证过程即使在更改后也能正常工作,但是当我尝试从数据库中 select 一个用户时,它只 returns 用户的特定部分,即 id、名称、电子邮件、电子邮件验证和图像 属性。 我怎样才能改变这种行为?
const user = await prisma.user.findUnique({
where: {
id: ...
}
})
当然我只能创建 Company 模型而不将它连接到 User 模型并且可能将用户的 id 添加到它以具有隐式连接,但这破坏了整个目的...
你正在寻找 nested reads,如果你想包括整个 company
模型你应该使用 include
和关系的名称,注意这将 return 该特定关系的所有字段:
const user = await prisma.user.findUnique({
where: {
id: ...
},
include: {
company: true,
},
})
如果你想 return 特定关系字段与整个 user
你应该在 include
:
select
const user = await prisma.user.findUnique({
where: {
id: ...
},
include: {
company: {
select : {
firstName: true,
},
},
},
})