Creating a model for a different user involves several steps that can be easily

Recently, I have been working on a project involving user interactions such as following other users and viewing their content. Using technologies like Prisma, GraphQL, and Nexus, I decided to create a following model today. The model structure is as follows:

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

After implementing this model, I realized that it only returned me as the user rather than the user I followed. My question now is how can I address this issue - should I create another model or make adjustments to the existing one?

Answer №1

It appears that each user requires the following functionalities:

  1. To add/remove User A as a follower of User B
  2. To find records of users who are following a specific user.
  3. To find records of users that a specific user is following.

Instead of creating a separate model, you can utilize a self-referencing many-to-many relation for this purpose. Here is how your User model would be structured in the Prisma Schema:

model User {
  id        String  @id @default(uuid())  // or any other unique id field

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

  // ...other fields in the user table
}

Managing followers for a specific user

If an existing user record needs to have another user added as a follower, you can do so like this:

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

You can also remove a user from the list of followers by changing the connect method to disconnect.

Locating a user's followers and following lists

This code snippet can help retrieve a user record along with their followers and followings:

 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
        },
    });

To delve deeper into self-relations, refer to the Prisma Docs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can the node_modules folder be archived from the project and subsequently uploaded to the Nexus Repository Manager?

An exclusive network initiative is searching for a package solution. Is there a way to efficiently upload all modules from the "node_modules" folder to Nexus Repository Manager in one go? If this can be accomplished, what steps should I take to achieve it ...

React component state remains static despite user input

I am currently in the process of developing a basic login/signup form using React, Typescript (which is new to me), and AntDesign. Below is the code for my component: import React, { Component } from 'react' import { Typography, Form, Input, But ...

What is the best way to set the typing of a parent class to the child constructor?

I am seeking a method to inherit the parameter types of a parent's constructor into the child's constructor. For example: class B extends A { constructor (input) { super(input); } } I attempted the following: class B extends ...

AngularJS Constants in TypeScript using CommonJS modules

Let's talk about a scenario where I need to select a filter object to build. The filters are stored in an array: app.constant("filters", () => <IFilterList>[ (value, label) => <IFilterObject>{ value: value, label: label } ]); i ...

Exploring the capabilities of AngularJS2's formGroup and formControlName functionality

Exploring the world of AngularJS2, I recently created a sign-up page utilizing formGroup formControlName, but encountered an issue with passing null values to the object. HTML code: <div class="col-md-8 col-md-offset-2"> <form [formGroup]="m ...

What steps do I need to take to export my TypeScript declarations to an NPM package?

I have multiple repositories that share similar functionality. I want to export type declarations to an NPM package so I can easily install and use them in my projects. Within the root directory, there is a folder called /declarations, containing several ...

What advantages does declaring a backing model "class" that closely resembles the GraphQL "Type" bring when using GraphQL?

I appreciate the Universal Relay Boilerplate for its meticulous organization and thoughtful structure compared to other boilerplates. It seems like they really put a lot of effort into ensuring everything is well-planned from the start, which is not always ...

Having trouble with gsap.reverse() not functioning properly when using onMouseLeave event in React

I've been incorporating simple gsap animations into my React application. I have successfully triggered an animation.play() function on onMouseEnter, but for some reason, the animation.reverse() function is not functioning as expected. Here's ho ...

What is the significance of the colon before the params list in Typescript?

Consider the following code snippet: import React, { FC } from "react"; type GreetingProps = { name: string; } const Greeting:FC<GreetingProps> = ({ name }) => { // name is string! return <h1>Hello {name}</h1> }; Wha ...

Challenges with Angular observables

Struggling to make observables work has been quite the challenge for me lately. My code now resembles a chaotic battleground rather than the organized structure it once was. The dreaded "ERROR TypeError: Cannot read property 'map' of undefined" ...

Incorporating lodash in a project with TypeScript and jspm

I seem to be missing something in my setup and would appreciate any assistance. I am working with TypeScript 2 + JSPM. I have tried various configurations in tsconfig using typeRoots and types (including adding the version number in the type name). Despite ...

React is unable to identify the property that was passed to a styled-component in Material UI

Custom Styled Component Using Material-UI: import { Typography } from '@material-ui/core'; const CustomText = styled(Typography)<TextProps>` margin-bottom: 10px; color: ${({ textColor }) => textColor ?? textColor}; font-size: ${( ...

What could be the reason for my dynamic image not appearing in a child component when using server-side rendering in Nuxt and Quasar

Currently, I am tackling SSR projects using Nuxt and Quasar. However, I encountered an issue when trying to display a dynamic image in a child component as the image is not being shown. The snippet of my code in question is as follows: function getUrl (im ...

Utilizing markModified inside a mongoose class that does not inherit from mongoose.Document

In my Typescript code using mongoose ODM, I am implementing a simple queue structure. The challenge arises when directly mutating an array instead of assigning a new value to it because mongoose doesn't automatically recognize the change. To resolve t ...

Refresh the mapbox source features in real-time

Currently, I am mapping out orders on a map with layers and symbols that have different statuses. When the status of an order changes, I want to update the color of the symbol accordingly. The layer configuration looks like this: map.addLayer({ id: &q ...

Setting up pagination in Angular Material can sometimes present challenges

After implementing pagination and following the guidelines provided here. This is my code from the app.component.ts file - import { Component, OnInit, ViewChild } from '@angular/core'; import {MatPaginator} from '@angular/material/paginat ...

Utilize functional JS code within a TypeScript environment

Attempting to integrate this code into a TypeScript project, it is a modified version of the react-custom-scrollbars. I am struggling with TypeScript in regards to declaring types for style and props. In this particular case, I prefer to bypass type check ...

Using an image as a button in Vue.js: A step-by-step guide

I'm currently working on creating a login button within a single-file-component using Vue.js in my Rails application with a Vue.js front-end. The purpose of this button is to redirect users to an external login page when clicked. I am wondering how I ...

Facing a challenge with handling HTTP data in a TypeScript-based Angular web application

I am currently working on developing a web application using Angular and the SpringMVC Framework. One of the tasks I'm facing is loading a list of users (referred to as "consulenti" in the code). While the backend HTTP request works fine, I encounter ...

The VueJS function is not defined

Looking for a way to fetch data from graphql in my vue project and store it in a variable. The function is asynchronous and the value of rawID needs to be awaited. However, there is a possibility that it could result in undefined, causing an error in the ...