Next 带有 Prisma 的 js:基于两个条件的 Upsert

Posted

技术标签:

【中文标题】Next 带有 Prisma 的 js:基于两个条件的 Upsert【英文标题】:Next js with Prisma: Upsert based on two conditions 【发布时间】: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,
    ,
  );

【问题讨论】:

【参考方案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,
    ,
)

【讨论】:

以上是关于Next 带有 Prisma 的 js:基于两个条件的 Upsert的主要内容,如果未能解决你的问题,请参考以下文章