如何在Prisma中通过单个Mutation更新多张关联表?
当然可以!Prisma的嵌套写操作正好能解决你的问题,完全不需要拆分两次mutation,单个user.update就能同时搞定User和关联Profile表的字段更新,而且还是原子性操作——要么全部更新成功,要么全部回滚,比两次独立操作更安全可靠。
直接看优化后的代码:
const { aboutMe, location, profession, firstName, lastName } = inputs; const updatedUser = await db.user.update({ where: { id: ctx.session!.userId }, data: { // 直接更新User表自身的字段 firstName, lastName, // 嵌套更新关联的Profile表 profile: { update: { aboutMe, location, profession, }, }, }, // 可选:如果需要返回包含Profile的完整用户数据,加上include include: { profile: true, }, });
补充说明:
如果你的业务场景中,用户可能还没有创建过Profile(也就是user.profile为null),可以把update换成upsert,这样会自动判断:Profile存在就更新,不存在就创建新的Profile记录:
profile: { upsert: { create: { aboutMe, location, profession }, update: { aboutMe, location, profession }, }, },
内容的提问来源于stack exchange,提问作者Kayote
相关产品推荐
相关产品推荐

