Prisma: difficulty connecting an explicit many to many relationship

I'm finding it difficult to connect an explicit many to many relationship with prisma. I have also tried to do the exact same thing with an implicit relationship and get the same result.

Stack: nodejs, prisma and apollo server

Schema:

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[]
}

Resolver:

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

Error:

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.

There is no information about connecting many to many relationships on the prisma docs. Can anyone tell me what I'm doing wrong?

1 answer

  • answered 2022-01-23 12:51 Danila

    To create a new relationship you need to create new record in UsersInvestments relation table. So you cannot connect to existing row, but you need to create new one. And data.users represent exactly this table, so you need to do following:

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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum