【问题标题】:Unique constraint failed on the constraint: `User_Account_userId_key` in prisma约束上的唯一约束失败:棱镜中的`User_Account_userId_key`
【发布时间】:2021-12-21 11:51:56
【问题描述】:

您好,我有三个型号

model User {
  user_id      Int      @id @default(autoincrement())
  email   String   @unique
  name    String?
  User_Account User_Account[]
}

model Account {
  account_id Int @id @default (autoincrement()) @unique
  email String 
  bank String
  createdAt DateTime @default(now())
  User_Account User_Account[]

}
model User_Account {
  id Int @id @default(autoincrement())
  accountId Int 
  userId Int 
  User User @relation(fields: [userId], references: [user_id])
  Account Account @relation(fields: [accountId], references: [account_id])
}

我正在尝试像这样播种我的数据库

const data = [
    {
      id: 1,
      email: 'pranit1@mf.com',
      name: 'Pranit1',
      bank: 'VCB',
      ids: [1,1]
    },
    {
      id: 2,
      email: 'pranit1@mf.com',
      name: 'Pranit1',
      bank: 'ACB',
      ids: [1,2]
    },
    {
      id: 3,
      email: 'pranit3@mf.com',
      name: 'Pranit3',
      bank: 'VCB',
      ids: [2,3]
    }
  ]
  const users = await prisma.$transaction(
    data.map(user =>
      prisma.user.upsert({
        where: { email: user.email },
        update: {},
        create: { name: user.name,
        email:user.email },
      })
    )
  );
  
  const accounts = await prisma.$transaction(
    data.map(account => 
      prisma.account.upsert({
        where: { account_id: account.id },
        update: {},
        create: { bank: account.bank ,
          email :account.email },
      })
    )
  );

  const user_accounts = await prisma.$transaction(
    data.map(uacc =>{
      console.log(uacc);
      return prisma.user_Account.upsert({
        where: { id: uacc.id },
        update: {id: uacc.id},
        create:{
          userId: uacc.ids[0],
        accountId: uacc.ids[1] },
      })}
    )
  );

但是我得到了一个

唯一约束在约束上失败:User_Account_userId_key

prisma studio中的数据生成如图

我只是尝试创建用户和帐户,并且一个用户可以与多个帐户相关联。它们的关系显示在 User_Account 表中。当我在 userId 上没有 @unique 标记时,我不明白为什么会出现唯一约束错误

【问题讨论】:

  • 您使用的是什么类型的数据库?试图重现,但使用 Postgres 对我来说效果很好

标签: javascript mysql prisma


【解决方案1】:

我无法重现我这边的错误。 但我怀疑你已经在数据库中有记录,它们与你的播种机的 ID 冲突。 此外,您可以对架构进行一些改进以使其更简单。

  1. 由于您没有关于多对多关系的任何额外详细信息,您可以摆脱 User_Account 模型并让 Prisma 为您处理。
  2. 在播种机上,您可以利用 Prisma 的嵌套功能,这样您就不必手动链接记录。这样,您就不必担心 ID。

schema.prisma 建议

model User {
  id       Int       @id @default(autoincrement())
  email    String    @unique
  name     String?
  accounts Account[]
}

model Account {
  id        Int      @id @unique @default(autoincrement())
  email     String
  bank      String
  users     User[]
  createdAt DateTime @default(now())
}

seed.js 建议

const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();

async function main() {
    const usersData = [
        {
            email: "pranit1@mf.com",
            name: "Pranit1",
            banks: ["VCB", "ACB"],
        },
        {
            email: "pranit3@mf.com",
            name: "Pranit3",
            banks: ["VCB"],
        },
    ];

    const users = await prisma.$transaction(
        usersData.map((user) =>
            prisma.user.upsert({
                where: { email: user.email },
                update: {},
                create: {
                    name: user.name,
                    email: user.email,
                    accounts: {
                        create: user.banks.map((bank) => ({
                            email: user.email,
                            bank,
                        })),
                    },
                },
            })
        )
    );
}

main()
    .catch((e) => {
        console.error(e);
        process.exit(1);
    })
    .finally(async () => {
        await prisma.$disconnect();
    });

【讨论】:

  • 感谢您的解决方案。我使用的是 Mysql,但我看不出不同的数据库如何为看似基本的模型提供不同的结果。
  • 不客气!我同意你的观点,只是让我对特定用例中可能存在的错误保持开放态度
猜你喜欢
  • 2019-04-28
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多