【问题标题】:Prisma: difficulty connecting an explicit many to many relationshipPrisma:难以连接明确的多对多关系
【发布时间】:2022-01-23 20:51:45
【问题描述】:

我发现很难将明确的多对多关系与 prisma 联系起来。我也尝试用隐式关系做同样的事情并得到相同的结果。

堆栈:nodejs、prisma 和 apollo 服务器

架构:

model User {
  id        Int    @id @default(autoincrement())
  ...
  ...
  investments UsersInvestments[]
}

model UsersInvestments {
  user         User       @relation(fields: [userId], references: [id])
  userId       Int
  investment   Investment @relation(fields: [investmentId], references: [id])
  investmentId Int

  @@id([userId, investmentId])
}

model Investment {
  id   Int            @id @default(autoincrement())
  ...
  ...
  users UsersInvestments[]
}

解析器:

createInvestment: async (_, { input }, { db, user }) => {
  const investment = await db.investment.create({
    data: {
      ...input
      users: {
        connect: { userId: user.id }
      }
    }
  });
      
  return investment
},

错误:

PrismaClientValidationError: 
Invalid `prisma.investment.create()` invocation:

{
  data: {
    ...
    ...
    users: {
      connect: {
        userId: 1
        ~~~~~~
      }
    },
+   userId: Int,
  }
}

Unknown arg `userid` in data.users.connect.userid for type UsersInvestmentsWhereUniqueInput. Did you mean `select`?
Argument userId for data.userId is missing.

在 prisma 文档中没有关于连接多对多关系的信息。谁能告诉我我做错了什么?

【问题讨论】:

    标签: node.js postgresql apollo-server prisma


    【解决方案1】:

    要创建新关系,您需要在UsersInvestments 关系表中创建新记录。所以你不能连接到现有的行,但你需要创建一个新的。而data.users正好代表这张表,所以你需要做以下事情:

    prisma.investment.create({
      data: {
        users: {
          // this creates new row in `UsersInvestments`
          create: [{
            // Here we say that this new row user will be one of existing users
            user: {
              connect: {
                id: 1
              }
            }
          }]
        }
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 2022-01-27
      • 1970-01-01
      • 2021-10-03
      • 2021-07-23
      • 2021-07-25
      • 2021-12-04
      • 2023-01-27
      • 2021-04-11
      相关资源
      最近更新 更多