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?
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
}
}
}]
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.