【问题标题】:creating objects for 1:n relation with prisma为 prisma 的 1:n 关系创建对象
【发布时间】:2022-02-21 01:10:13
【问题描述】:

我有两个模型,Fish 和 BoardFish 具有 1:1 的关系 - BoardFish 是 Fish 的一种 我用命名类型创建了一些种子鱼。

如何在 Prisma 中做到这一点?我想我有架构设置,但是除了花哨/嵌套类型之外,插入数据并没有真正记录。

架构:

model Fish {
    name      String      @id
    boardFish BoardFish[]
}

model BoardFish {
    id       Int    @id @default(autoincrement())
    name     String
    fishType Fish   @relation(fields: [name], references: [name])
}

尝试创建:

        let fishes = []
        for (let c = 0; c < fishCount; c++) {
            const fishType = await prisma.fish.findFirst({ where: { name: 'salmon' } })
            const fishData = {
                fishType: fishType!.name,
                // name: 'salmon',
                px: 0,
                py: 0,
            }
            const fish = await prisma.boardFish.create({ data: fishData })
            fishes.push(fish)
        }

但我无法插入:

→ 35 const fish = await prisma.boardFish.create({
       data: {
         fishType: 'salmon',
                   ~~~~~~~~
         px: 3,
         py: 5
       }
     })

Argument fishType: Got invalid value 'salmon' on prisma.createOneBoardFish. Provided String, expected FishCreateNestedOneWithoutBoardFishInput:
type FishCreateNestedOneWithoutBoardFishInput {
  create?: FishCreateWithoutBoardFishInput | FishUncheckedCreateWithoutBoardFishInput
  connectOrCreate?: FishCreateOrConnectWithoutBoardFishInput
  connect?: FishWhereUniqueInput
}

所涉及的类型很难理解,Prisma 似乎真的用数千行自动生成的代码占据了大多数“魔法”的蛋糕,而我一直在挖掘这些代码,但运气不佳。

【问题讨论】:

  • 两件事;第一:如果您想要 1:1 关系,请编辑您的 prisma 模式以删除 boardFish BoardFish[] 上的方括号,第二:使用 prisma 的 connect api 创建相关记录。看起来您只是在使用字符串 'salmon'
  • 是的,谢谢,我错过了connect 上的文档,但很有意义!

标签: typescript orm prisma


【解决方案1】:

如果你想拥有 1:1 的关系,我认为架构需要看起来更像这样:

model Fish {
    name      String      @id
    boardFish BoardFish? // removed autogenerated `[]` and made optional
}

model BoardFish {
    id       Int    @id @default(autoincrement())
    name     String
    fishType Fish   @relation(fields: [name], references: [name])
}

创建相关记录时,使用prisma的connectapi

const fish = await prisma.boardFish.create({
  data: {
    fishType: {
      connect: { name: 'salmon' }, // or `connectOrCreate` if it doesn't exist
    },
  }
})

【讨论】:

  • 嘿,这工作谢谢!我错过了connect 文档
猜你喜欢
  • 2021-02-20
  • 2022-10-25
  • 2021-05-03
  • 2011-10-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 2018-01-31
相关资源
最近更新 更多