【问题标题】:Next js with Prisma: Upsert based on two conditionsNext 带有 Prisma 的 js:基于两个条件的 Upsert
【发布时间】:2022-01-04 01:19:09
【问题描述】:

我正在尝试使用 Prisma 执行以下操作:

如果存在具有相同哈希和 user_id 的类别行,只需更新它的“名称”字段,否则,创建行

这可能吗? TS 给我一个错误,说“where”上给出的键的类型必须是 categoriesWhereUniqueInput,但是 hash 和 user_id 都不是唯一的,它们可以重复,这是两者之间的组合将是唯一的

我该如何解决这个问题?我是否必须手动检查是否有 id 并根据它更新/创建?

提前非常感谢!

  const category = await prisma.categories.upsert({
    where: {
      hash,
      user_id: id,
    },
    update: {
      name,
    },
    create: {
      hash,
      name,
      user_id: id,
    },
  });

【问题讨论】:

    标签: reactjs postgresql next.js prisma


    【解决方案1】:

    当字段组合是唯一的时,Prisma 将为where 条件生成一个新类型,它基本上只是所有相关字段的名称加上_

    查看categoriesWhereUniqueInput 以了解名称。很可能它被称为user_id_hashhash_user_id

    这就是查询的大致样子:

    const category = await prisma.categories.upsert({
        where: {
            user_id_hash: {  // user_id_hash is the type generated by Prisma. Might be called something else though. 
                user_id: 1,
                hash: "foo"
            }
        },
        update: {
            name: "bar",
        },
        create: {
            hash: "foo",
            name: "bar",
            user_id: 1,
        },
    })
    
    

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 2021-05-11
      • 1970-01-01
      • 2013-11-04
      • 1970-01-01
      • 2020-12-18
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多