【问题标题】:How to upsert new record in Prisma without an ID?如何在没有 ID 的情况下在 Prisma 中插入新记录?
【发布时间】:2019-08-19 15:24:26
【问题描述】:

我正在使用 Prisma (https://www.prisma.io) 作为 ORM。我想在存储数据时检查重复项,如果不存在,则创建一条新记录。

我想我可以使用 Prisma 提供的 upsert 方法来做到这一点,并且在生成的客户端中可用,但是该方法的 where 子句仅适用于 id (或 @unique 字段),但如果记录不存在,则没有要提供的 id。

我提供了一个问题的例子。

datamodel.prisma

type System {
  id: ID! @unique
  performances: [SystemPerformance!]! @relation(name: "PerformanceBySystem" onDelete: CASCADE)
  name: String! @unique
}

type SystemPerformance {
  id: ID! @unique
  system: System! @relation(name: "PerformanceBySystem")
  date: DateTime!
  perf1: Float
  perf2: Float
}

seed.js

const { prisma } = require('./generated/prisma-client');
async function main(){
  await prisma.createSystem({
    name: 's1',
  });
  await prisma.createSystem({
    name: 's2',
  });
  await prisma.createSystem({
    name: 's3',
  });
}
main();

创建后有一个包含三个没有性能的系统的数据库。如果没有任何具有相同日期和相同系统的系统,我正在尝试插入一个新的 SystemPerformance。我试过了

const { prisma } = require('./prisma/generated/prisma-client');

const perf = await prisma.upsertSystemPerformance({
       where: {
         system: {name: 's1'},
         date: "2019-03-12T00:01:06.000Z"
       },
       update: {
         perf1: 13.45,
         perf2: 18.93
       },
       create: {
        system: {
            connect: { name: 's1' }
        },
        date: "2019-03-12T00:01:06.000Z",
        perf1: 13.45,
        perf2: 18.93
       }
})

但是抛出异常:

UnhandledPromiseRejectionWarning:错误:“SystemPerformanceWhereUniqueInput!”类型的变量“$where”预期值!但得到:{“系统”:{“名称”:'s1'},“日期”:“2019-03-12T00:01:06.000Z”}。原因:“system”字段“system”未在输入类型“SystemPerformanceWhereUniqueInput”中定义

我找到的唯一解决方案是检查存在,然后更新或创建,但我想用 upsert 来做。

let check = await prisma.$exists.SystemPerformance({
            system: {name: 's1'},
            date: "2019-03-12T00:01:06.000Z"
        });
let perfo;
if (check){
  const sysPerf = await prisma.systemPerformances({where:{system: {name: 's1'}, date: "2019-03-12T00:01:06.000Z"}})
            .$fragment(`
            {
                id
            }
            `);
  perfo = await prisma.updateSystemPerformance({
    where: {id: sysPerf[0].id},
            data: {
              perf1: 13.45,
              perf2: 18.93
            }
   })
}
else {
  perfo = await prisma.createSystemPerformance({
    system: {
      connect: { name: 's1' }
    },
    date: "2019-03-12T00:01:06.000Z",
    perf1: 13.45,
    perf2: 18.93
  }
})

有没有办法通过 upsert 做到这一点?

【问题讨论】:

  • Upsert 仅接受唯一字段作为 where 子句中的输入。我担心您将不得不使用解决方法来查询记录,然后根据记录是否存在使用 upsert 或更新/创建。
  • 我害怕那个。我问是否有更好的解决方案。谢谢你的回答。

标签: node.js prisma prisma-graphql


【解决方案1】:

where 中的字段必须是唯一的。

如果您可以创建一些字段,比如说date @unique (date: DateTime! @unique),并将其用于您在 upsert 中的位置,我认为它会起作用(在我的本地测试)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 2015-05-24
    • 1970-01-01
    相关资源
    最近更新 更多