简体   繁体   中英

Mongodb Prisma 2 many to many relation is working 1 sided

I have a small issue with the relational data table, here is my model, and the question is below this.

model User {
  id                    String     @id @default(dbgenerated()) @map("_id") @db.ObjectId
  createdAt             DateTime   @default(now())
  updatedAt        DateTime   @updatedAt
  email                 String     @unique
  firstName             String
...
  rsvpedSessions        Session[]  @relation("Rsvped", fields: [rsvpedSessionId])
  rsvpedSessionId       String[]   @db.Array(ObjectId)
  notRespondedSessions  Session[]  @relation("notResponded", fields: [notRespondedSessionId])
  notRespondedSessionId String[]   @db.Array(ObjectId)
  declinedSessions      Session[]  @relation("Declined", fields: [declinedSessionId])
  declinedSessionId     String[]   @db.Array(ObjectId)


model Session {
  id                 String   @id @default(dbgenerated()) @map("_id") @db.ObjectId
  createdAt          DateTime @default(now())
  updatedAt    DateTime @updatedAt
  title              String
  ...
  rsvpedUsers        User[]   @relation("Rsvped", fields: [rsvpedUserId])
  rsvpedUserId       String[] @db.Array(ObjectId)
  notRespondedUsers  User[]   @relation("notResponded", fields: [notRespondedUserId])
  notRespondedUserId String[] @db.Array(ObjectId)
  declinedUsers      User[]   @relation("Declined", fields: [declinedUserId])
  declinedUserId     String[] @db.Array(ObjectId)

when I create the session by adding the user to the notResponded. I can see the user in notResponded array but, on User, I can't get the session under notRespondedSessions. It just links the user to the session but it doesn't link the session to the user.

I create the session with

return await prisma.session.create({
        data: {
          ...args,
          notRespondedUserId: args.userID,
        },
      });

and one more detail, when I try to Connect on notRespondedUsers, it says connect is not a valid arg.

do you have any idea what might be the reason?

If you want to create a session and connect it to an existing user record, you should use the connect API with the relation field in question ( notRespondedUsers ) instead of trying to assign a value directly to notRespondedUserId .

I think this is the query you're looking for:

    await prisma.session.create({
        data: {
            ...args
            notRespondedUsers: {
                connect: {
                    id: args.userID   // if there is more than one user, you can also pass an array of { id: string} objects to connect
                }
            }
        },
    });

You can find the syntax and details for connect in the Prisma docs .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM