You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Prisma更新字段时出现‘not assignable to type’错误求助

解决Prisma基于外键更新Patient时的类型错误

错误原因

你碰到的Type '{ authorId: number; }' is not assignable to type 'PatientWhereUniqueInput'.错误,本质是Prisma的update方法要求where条件必须指向带唯一约束的字段(比如主键id、标注@unique的字段)。你的authorId只是外键,没有唯一约束——一个User可以关联多个Patient,Prisma无法确定要更新哪一条记录,所以报错。


解决方案

方案1:指定Patient的唯一标识(推荐)

如果业务逻辑是用户修改自己名下的某一条特定Patient,需要传入目标Patient的id(主键)来精准定位,同时保留authorId做权限校验:

const updatedPatient = await prisma.patient.update({
  where: {
    id: patientId, // 从请求参数中获取要更新的Patient ID
    authorId: userId, // 确保只能修改自己的Patient
  },
  data: body,
});
return updatedPatient;

方案2:更新用户名下所有Patient(用updateMany)

如果需求是更新当前用户关联的全部Patient记录,需要改用updateMany方法(update只支持单条唯一记录更新):

const updatedResult = await prisma.patient.updateMany({
  where: {
    authorId: userId,
  },
  data: body,
});
return updatedResult; // 返回更新的记录数量等信息

方案3:给authorId添加唯一约束(仅适用于一对一场景)

如果你的业务确实要求一个User只能对应一个Patient,可以给authorId加上@unique约束:

model Patient {
  id Int @id @default(autoincrement())
  firstName String
  lastName String
  email String @unique
  password String
  contact String
  address String
  dob String
  image String?
  authorId Int @unique // 新增唯一约束
  author User @relation(fields: [authorId], references: [id])
  specialAttention Boolean @default(false)
}

添加后authorId成为唯一字段,就能直接用where: {authorId: userId}调用update方法,但这个方案只适用于严格一对一的用户-患者关系。


内容的提问来源于stack exchange,提问作者Arpit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 23:33:13