How to create model for other User

Viewed 449

ive been working on a project and i recently starting on users following other users and seeing there content im using(prisma, graphql, and nexus) so today i created a following model it looks like this

model Following {
id       Int    @id @default(autoincrement())
followId Int
User     User?  @relation(fields: [userId], references: [id])
userId   Int?
}

Ii thought this would work but i realized that it would just return me as the user and not the user i followed so my question is how can i fix this problem would i create another model or just readjust some things on the current one

2 Answers

If I'm not mistaken, for each user you need the following:

  1. Be able to add/remove User A to the followers of User B
  2. Find User records that follow a certain user.
  3. Find User records a certain user is following.

You don't necessarily need to explicitly define a separate model. Instead, you can use a many-to-manyself-relation for this. Here is what your User model would look like in the Prisma Schema

model User {
  id        String  @id @default(uuid())  // or whatever your unique id field is. 

  following User[]   @relation("UserFollows", references: [id]) 
  followers User[]   @relation("UserFollows", references: [id])

  // ...other fields in user table
}

Add/Remove followers for a certain user

If a user record already exists, you can add another user as a follower like this:

const updatedUser = await prisma.user.update({
        where: {
            id: followedUserId,
        },
        data: {
            followers: {
                connect: {   // change to disconect for removing a follower. 
                    id: followerUserId,
                },
            },
        },
    });

You can also remove a user from another user's followers by changing the connect call to a disconnect call.

Find a user's followers and following lists.

You can do this to fetch a user record along with their follower and following lists.

 const user = await prisma.user.findUnique({
        where: {
            id: userId,
        },
        include: {
            followers: true,   // list of followers for userId
            following: true,   // list of users that follow userId
        },
    });

You can learn more about self relations in this concept guide at the Prisma Docs.

Related