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

Prisma写入查询中如何将球员当前值存入选单项

解决方案:创建Team时同步保存球员选中时的value到Selection

要实现这个需求,你需要先批量查询出目标球员当前的value,再将这些数据作为静态值传入Selection的创建逻辑中——因为createMany无法在嵌套创建时动态关联获取Player的实时字段值。

具体实现步骤

  1. 批量查询目标球员的ID和当前value
    先根据POST请求传入的球员ID数组,从数据库中获取对应的id和value,仅查询需要的字段能提升性能:
const playerIds = [78410, 71359, 76341]; // 示例传入的球员ID数组
const playersWithValue = await prisma.player.findMany({
  where: { id: { in: playerIds } },
  select: { id: true, value: true }
});
  1. 创建Team并批量生成Selection
    将查询到的球员数据转换为createMany需要的格式,嵌套在team.create中完成关联创建:
const newTeam = await prisma.team.create({
  data: {
    userId: <userId>, // 替换为实际的用户ID
    selections: {
      createMany: {
        data: playersWithValue.map(player => ({
          playerId: player.id,
          value: player.value // 存入选中时的球员value快照
        }))
      }
    }
  },
  // 可选:返回创建后的Team及关联的Selections
  include: { selections: true }
});

关键补充

如果担心查询球员value和创建Team这两步之间,球员的value发生变化,可以用数据库事务包裹操作,保证数据一致性:

const newTeam = await prisma.$transaction(async (tx) => {
  const playersWithValue = await tx.player.findMany({
    where: { id: { in: playerIds } },
    select: { id: true, value: true }
  });
  return tx.team.create({
    data: {
      userId: <userId>,
      selections: {
        createMany: {
          data: playersWithValue.map(p => ({ playerId: p.id, value: p.value }))
        }
      }
    },
    include: { selections: true }
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 23:45:08