If I'm not mistaken, for each user you need the following:
- Be able to add/remove
User A to the followers of User B
- Find
User records that follow a certain user.
- 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.