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

如何使用Prisma事务创建账户后关联插入交易记录?

Prisma事务中关联创建账户与交易记录的正确实现

问题所在

你当前用数组形式的$transaction执行操作,但这种方式是并行执行的,两个操作同时发起,根本拿不到刚创建的账户ID。你写的prisma.account.fields.id只是模型的字段引用,不是实际创建出来的账户ID,所以交易记录的accountId无法正确关联。

正确写法(Prisma v5)

改用异步函数形式的事务,它能让你按顺序执行操作,还能拿到前一步的执行结果:

const { accountObj, transaction } = await prisma.$transaction(async (tx) => {
  // 第一步:创建账户
  const accountObj = await tx.account.create({
    data: {
      accountCode: Number(accountCode),
      name: name?.trim(),
      type,
      description,
      balance: Number(balance),
      status,
      branchId,
      createdById: req.user.id,
    },
  });

  let transaction = null;
  // 余额大于0时,创建关联的开户交易
  if (Number(balance) > 0) {
    transaction = await tx.transaction.create({
      data: {
        type: 'OPENING_BALANCE',
        amount: Number(balance),
        reference: uuidv4(),
        description: `Account opening balance for ${name?.trim()} account created by ${req.user.name}`,
        status: 'ACTIVE',
        branchId,
        accountId: accountObj.id, // 直接使用刚创建的账户ID
        createdById: req.user.id,
      },
    });
  }

  return { accountObj, transaction };
});

核心要点

  • 必须用async (tx) => {...}这种形式的事务,确保操作按顺序执行,能获取前一步创建的账户对象。
  • 事务内部所有数据库操作都要使用传入的tx对象,不能用全局的prisma,这样才能保证所有操作在同一个事务中,要么全部成功,要么全部回滚。
  • 交易记录的accountId直接取accountObj.id,确保关联的是刚创建的目标账户。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 02:32:10