Marcel Dz
Marcel Dz

Reputation: 2714

Add a contact with by using self relation with prisma

I have the following prisma schema

model User {
  userId        Int         @id @default(autoincrement())
  registeredAt  DateTime   @default(now())
  firstName     String      @db.VarChar(250)
  lastName      String      @db.VarChar(250)
  email         String      @db.VarChar(250)
  password      String      @db.VarChar(250)
  socketId      String?      @db.VarChar(250)
  role          String     @default("user")
  confirmedAccount  DateTime?
  contacts User[]  @relation("ContactsList")
  addedByContacts  User[]  @relation("ContactsList")
}

I decided to use a self relation for the user model so I can add contacts and query for them in my web app. Query on the contacts of the user does work fine, but im stuck adding contacts to a user. Does somebody see what I have to change in my code? the statement is not working.

try {
    const addUser = await prisma.user.update({
      where: {
        userId: id
      },
      data: {
        contacts: { 
          create: {
            data: {userId: 6} // <- hardcoded testing with this id which i want to add to the current user who is defined by id
          }
        }
      }
    })
    res.status(201).json({ message: 'Added contact' });
  } catch (error) {
    res.status(422).json({ message: error });
    return;
  }

 

Upvotes: 0

Views: 313

Answers (1)

Marcel Dz
Marcel Dz

Reputation: 2714

I stumbled over the solution. For everyone facing issues on updating values on self relations, I had to use connect to make it work.

This is my end result:

  try {
    const addUser = await prisma.user.update({
      where: {
        userId: id
      },
      data: {
        contacts: { 
          connect: {
            userId: contactId
          }
        }
      }
    })
    res.status(201).json({ message: 'Added contact' });
  } catch (error) {
    res.status(422).json({ message: error });
    return;
  }

Upvotes: 1

Related Questions