Prisma:难以连接明确的多对多关系

Prisma: difficulty connecting an explicit many to many relationship

我发现很难将明确的多对多关系与 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 文档上没有关于连接多对多关系的信息。谁能告诉我我做错了什么?

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

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
          }
        }
      }]
    }
  }
});