'How to create two way connection in my Prima model?

I am creating a WhatsApp clone with nestjs and Prisma, as of now, I have a simple User model like this with an implicit friends relation (I need it to be two-way, so If I(User A) add someone as my friend(User B), he should also have me as a friend). Currently, my User model looks like this,


model User {
  id              Int     @id @default(autoincrement())
  username        String  @unique() @db.VarChar(255)
  email           String  @unique() @db.VarChar(255)
  avatar          String? @db.VarChar(255)
  password        String  @default("1") @db.VarChar(255)
  friends         User[]  @relation("friends")
  friendsRelation User[]  @relation("friends")
  hashRT          String? @db.VarChar(255)

  @@map("users")
}

And I tried using this query to add an user as current user's friend,

  async addFriend(userId: number, friendId: number) {
    const user = await prisma.user.update({
      where: {
        id: userId,
      },
      data: {
        friends: {
          connect: {
            id: friendId,
          },
        },
      },
      include: {
        friends: true,
      },
    });
    return user;
  }

with this, when I query to get the user's friend list using the following query, I get the new friend in the result(so he was added successfully)

  async getFriends(userId: number) {
    const user = await prisma.user.findFirst({
      where: {
        id: userId,
      },
      include: {
        friends: true,
      },
    });
    return user.friends;
  }

So I'm confident that the friend was added successfully. However, when I do the same query for the new friend, his friends' array is empty. Meaning he doesn't know that he has a friend. But I want the relationship to be two-way, so when I add someone as a friend(User B) of UserA, I need the current User A to be set as a friend. of User B as well. I got it to work with two queries,


 async addFriend(userId: number, friendId: number) {
    const user = await prisma.user.update({
      where: {
        id: userId,
      },
      data: {
        friends: {
          connect: {
            id: friendId,
          },
        },
      },
      include: {
        friends: true,
      },
    });
    //also add user to friend's friends
    await prisma.user.update({
      where: {
        id: friendId,
      },
      data: {
        friends: {
          connect: {
            id: userId,
          },
        },
      },
      include: {
        friends: false,
        _count: false,
        friendsRelation: false,
      },
    });
    return user;
  }

Is this the correct way of doing this? Or is there any predefined way of handling this? I'm open to schema changes if they can help with this situation.

I'm using prisma version 3.12.0 and MySQL as the provider.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source