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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 09:23:11