What are the best methods for querying and updating a self-relation in Prisma?

I recently obtained some self-relation tables directly from a specific Prisma example.

model User {
  id         Int       @id @default(autoincrement())
  name       String?
  followedBy Follows[] @relation("follower")
  following  Follows[] @relation("following")
}

model Follows {
  follower    User @relation("follower", fields: [followerId], references: [id])
  followerId  Int
  following   User @relation("following", fields: [followingId], references: [id])
  followingId Int

  @@id([followerId, followingId])
}

I am contemplating the most effective way to determine if one user is following another, as well as methods for following and unfollowing. My initial thought is to directly query/update the Follows table, but I'm uncertain if the followedBy and following fields in the User model will automatically update themselves.

Answer №1

Consider this scenario:

  1. Adding a new user:
  const createUser = await prisma.user.createMany({
    data: [
      {
        name: 'user1',
      },
      {
        name: 'user2',
      },
      {
        name: 'user3',
      },
    ],
  });
  1. Establishing follow relationships
  const establishFollows = await prisma.follows.createMany({
    data: [
      {
        followerId: 1,
        followingId: 2,
      },
      {
        followerId: 1,
        followingId: 3,
      },
      {
        followerId: 2,
        followingId: 3,
      },
    ],
  });
  1. To determine the followers of user 1, you can do so through both the user and follows models as shown below:
  const findUserFollowers = await prisma.socialUser.findMany({
    where: {
      following: {
        some: {
          followerId: 1,
        },
      },
    },
  });

  console.log('findUserFollowers', findUserFollowers);

  const findFollowsFollowers = await prisma.follows.findMany({
    where: {
      followerId: 1,
    },
    include: {
      following: true,
    },
  });

  console.log('findFollowsFollowers', findFollowsFollowers);

Here is the result:

findUserFollowers [ { id: 2, name: 'user2' }, { id: 3, name: 'user3' } ]

findFollowsFollowers [
  {
    followerId: 1,
    followingId: 2,
    following: { id: 2, name: 'user2' }
  },
  {
    followerId: 1,
    followingId: 3,
    following: { id: 3, name: 'user3' }
  }
]

To handle unfollow actions, the record must be explicitly deleted from the follows table.

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

Selecting the initial option as the default in a drop-down menu

How can I use Jquery to add a new row and set the default value of a dropdown list? var selectVal = $(parent).children().first().find('select').find('option[selectedGivenTo="true"]').val(); var newSelect = $(parent).children().last ...

Transferring Visitor's Country Code Between Two Web Applications Using .NET Framework (ASP/MVC)

I'm currently working on developing an application that collects user information such as country, city, and IP address of the website they're visiting. This data is then sent to another web application of mine, which will be automatically update ...

Placing a user's username within an ejs template using express and node.js

Currently, I am attempting to integrate the username into a layout using ejs templating with node and express. Below are the steps I have taken: Mongodb model: const mongoose = require('mongoose') const Schema = mongoose.Schema; var uniqueValid ...

there is no minimum height specified for the table

Hey there! I'm working on a dynamic table that I populate using data from my API. However, I'm facing an issue where I want the table to maintain a minimum height when there are only a few results, but I can't seem to make it work. I attemp ...

Issue arising from JQuery libraries when utilizing Webpack

Having an issue with my form renderer JS script. When making an AJAX request to retrieve it, it applies functions and properties to jQuery for rendering a form. However, due to the use of webpack with another framework, there are two jQuery contexts causin ...

Aligning text using Javascript and dynamically resizing it with css3 viewport causes a choppy effect when adjusting the size

I'm encountering some issues with keeping my text centered and smoothly resizing when the window size changes. I have a weather website that showcases only the temperature. I present the temperature in various ways. I utilize local storage to store t ...

On Windows systems, where exactly does npm place its packages during installation when using Node version 10.x

Does anyone know where I can locate the locally installed npm modules when using NodeJS version 10? I have checked under C:\Users\MyUser\AppData\Roaming, but I cannot find the "npm" folder. ...

The button's onclick function is failing to save the record in the database

Hello everyone, I am facing an issue with the ONCLICK button functionality. I have written code to save a form to the database. In the image, there are 2 buttons: Save button (type="submit") Save and New button (type="button") The Save button is ...

Issue with Bootstrap 4 tab.js not updating active states

I am having trouble with 2 out of the 4 tab.js examples in both CodePen and a local HTML file. The "nav" example is causing the items in the dropdown to stay active and inaccessible after clicking. The same issue occurs with all the items in the vertical t ...

What is the best method for dynamically loading CSS using JavaScript?

Due to a certain condition I have, I am unable to load some CSS and JS in my HTML. As a solution, I've decided to dynamically pull them using $.get(). While I have successfully tested pulling and executing js remotely, I am facing some challenges when ...

"Utilizing Jest Globals to Provide an Empty Input for a Function: A Step-by-

I have developed a function that outputs null when the input is empty: const testFunc = (param) => { if (param) { //blabla } return null; }; To verify the return null behavior with an empty param, I want to utilize describe...it...: describe( ...

Resize a span's width using the width of another element using only CSS

Website Development <div class="container"> <div id="setter"> <span>some unique content here</span> </div> <div class="wrap"> <span> different text goes here, different text goes here, diffe ...

Interact with a modal element using puppeteer

I'm having trouble clicking on the email login button inside a modal using Puppeteer for automation. The code is not able to find the modal element. Can someone assist me in debugging this issue? const puppeteer = require('puppeteer'); ( ...

What is the best method for streaming files from Java to the browser while preventing the user from downloading and saving the file?

I'm new to this and feeling a bit lost. Here's the situation: I have a web app (built with JavaScript/Reactjs) and a backend (Java using Liferay API) The server contains files (File A, B, C, etc.) of various types: pdf, excel, audio, txt, etc. ...

Exploring the capabilities of TabrisJs in conjunction with Upnp technology

Working with Upnp in TabrisJs seems to be a bit challenging. Even though it has good support for node packages, I am facing difficulties while dealing with Upnp. I included node-upnp-client in my package.json file. "dependencies": { "tabris": "^2.0 ...

"Steps to retrieve the button's ID when using the onClick event in Reactjs

Currently, I am working with Reactjs and Nextjs. I am utilizing functional components instead of classes. Within a loop, I have buttons and I am attempting to retrieve the id of the button when clicked using "onClick". Unfortunately, I am encountering th ...

Tips for adjusting HTML files prior to HTMLOutput in Google Apps Script

I'm looking to make some changes to an HTML file within the doGet() function before it's output in HTMLOut. However, I'm running into an issue with the <?!=include('css').getContent();?> code snippet, as it can't be exec ...

What is the best way to navigate through a webpage to find a specific folder and show its contents on the page?

My goal is to design a webpage where users can browse their computer for a specific folder, select it, and have its content displayed on the webpage. I am fairly new to creating pages, but I want to develop a platform where you can easily find and view f ...

Invoke a public method in TypeScript

I'm a newcomer to typescript. In my node-express application, I am trying to call a public function. However, I keep encountering an issue where this is always undefined, leading to errors whenever I attempt to call the public function. Below is the s ...

Is it possible to pass a random variable into an included template in Jade?

In my jade template called 'main page', I have a reusable template named 'product template'. The 'product template' is designed to display dynamic data and needs to be flexible enough to be used in multiple pages without being ...