【问题标题】:How to create a new many to many relationship with existing records?如何与现有记录创建新的多对多关系?
【发布时间】:2022-01-27 00:16:05
【问题描述】:

我有一个多对多关系建模拳击比赛:

  • 一场战斗可以有多个战士(总是 2 个)
  • 一名战士可以参加多次战斗

我的架构如下所示:

model Fight {
  id            Int     @id @default(autoincrement())
  fighters      FighterFights[]
}

model Fighter {
  id        Int     @id @default(autoincrement())
  name      String  @unique
  fights    FighterFights[]
}

model FighterFights {
  fighter      Fighter     @relation(fields: [fighterId], references: [id])
  fighterId    Int
  fight        Fight @relation(fields: [fightId], references: [id])
  fightId      Int

  @@id([fighterId, fightId])
}

我想用 2 名现有战士创建新的战斗。这是我尝试过的:

const result = await prisma.fight.create({
  data: {
    fighters: {
      connect: [{ id: fighter1 }, { id: fighter2 }],
    },
  },
})

但我收到此打字稿错误:

Type '{ id: any; }' is not assignable to type 'FighterFightsWhereUniqueInput'.
  Object literal may only specify known properties, and 'id' does not exist in type 'FighterFightsWhereUniqueInput'.

我的prisma.fight.create 函数调用应该是什么样子?

【问题讨论】:

    标签: typescript postgresql many-to-many prisma


    【解决方案1】:

    你可以这样做:

    const { PrismaClient } = require('@prisma/client')
    const prisma = new PrismaClient()
    
    const saveData = async () => {
      const fighter1 = await prisma.fighter.create({
        data: {
          name: 'Ryu',
        },
      })
      const fighter2 = await prisma.fighter.create({
        data: {
          name: 'Ken',
        },
      })
    
      console.log(JSON.stringify(fighter1, null, 2));
      console.log(JSON.stringify(fighter2, null, 2));
    
      const fight = await prisma.fight.create({
        data: {
          fighters: {
            createMany: {
              data: [
                {
                  fighterId: fighter1.id,
                },
                {
                  fighterId: fighter2.id,
                },
              ]
            },
          },
        },
        select: {
          id: true,
          fighters: {
            select: {
              fighter: true,
            },
          },
        },
      });
    
      console.log(JSON.stringify(fight, null, 2));
    }
    
    saveData()
    

    它将返回以下内容

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 2015-10-22
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 2012-09-17
      • 2017-08-25
      相关资源
      最近更新 更多