prisma connectOrCreate 创建重复项或返回错误

问题描述 投票:0回答:1

我正在尝试在与另一个表具有多对多关系的表上播种一堆记录。

model Resume {
  id          Int       @id @default(autoincrement())
  name        String
  company     String? 
  logo        String?
  description String?
  startDate   DateTime?
  endDate     DateTime?
  createdAt   DateTime? @default(now()) @map("created_at")
  updatedAt   DateTime? @map("updated_at")
  deletedAt   DateTime? @map("deleted_at")
  tags        ResumeTag[]

  @@map("resume")
}

model ResumeTag {
  id          Int       @id @default(autoincrement())
  name        String    @unique
  resume      Resume[]

  @@map("resume_tags")
}

在脚本上,这就是我使用的

connectOrCreate
(删除了其他部分,但这就是它的要点):

const resumeSingle = {
    id: 1,
    company: 'Company A',
    name: 'Software Developer',
    logo: 'Logo.svg',
    description: '',
    startDate: moment('2016-06-01').toISOString(),
    endDate: null,
    tags: ['Node.JS', 'GraphQL', 'PostgreSQL']
  };
const { tags, ...resumeData} = resumeSingle;

await prisma.resume.create({
 data: {
  ...resumeData,
   tags: {
    connectOrCreate: tags.map(tag => ({
      where: { name: tag }, create:  { name: tag } 
    }))
   },
  },
 });

我有几条记录要插入,有些记录有相同的重复

tags
。但是,只有当新记录在数据库中已有标签时,代码才会因错误而停止。

Unique constraint failed on the constraint: `name`.

如果我删除

unique
name
列上的
ResumeTag
,它只会在数据库表中添加重复项(具有相同的名称)。

我在这里使用

connectOrCreate
错了?

node.js prisma
1个回答
0
投票

应该使用

prisma.$transaction()
以避免
Unique constraint failed on the constraint
错误

    const resumeSingle = {
        id: 1,
        company: 'Company A',
        name: 'Software Developer',
        logo: 'Logo.svg',
        description: '',
        startDate: moment('2016-06-01').toISOString(),
        endDate: null,
        tags: ['Node.JS', 'GraphQL', 'PostgreSQL']
      };
    const { tags, ...resumeData} = resumeSingle;
    
    // remove await here
    const dbTask = prisma.resume.create({
     data: {
      ...resumeData,
       tags: {
        connectOrCreate: tags.map(tag => ({
          where: { name: tag }, create:  { name: tag } 
        }))
       },
      },
     });

     //The solution here
     const resume  = await prisma.$transaction([...dbTask])
© www.soinside.com 2019 - 2024. All rights reserved.