Next js with Prisma:基于两个条件的更新插入

Gab*_*el 6 postgresql reactjs next.js prisma

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

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

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

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

预先非常感谢!

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

Tas*_*mam 7

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

看看categoriesWhereUniqueInput看看名字是什么。最有可能的是它被称为user_id_hashor hash_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,
    },
})

Run Code Online (Sandbox Code Playgroud)


Amc*_*tty 5

以防万一有人偶然发现这一点:如果您在子句中找不到用于whereselect by 的选项user_id_hash,那么您需要首先在表定义中声明唯一的复合约束。

 @@unique([fieldOne, fieldTwo])
Run Code Online (Sandbox Code Playgroud)

执行此操作后,您将能够在代码中选择,条件是wherefieldOne_fieldTwo