Home > Blockchain >  How to query/update a self-relation in Prisma?
How to query/update a self-relation in Prisma?

Time:03-17

I have some self-relation tables taken directly from one of Prisma's examples.

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 wondering on the best/most idiomatic way to determine whether a user is following another user, as well as operations for following and unfollowing. I'm thinking the best way is to just query/update the Follows table directly, but I'm unsure whether the followedBy and following fields in the User model will automatically update themselves.

CodePudding user response:

Consider this example:

  1. Creating a user:
  const createUsers = await prisma.user.createMany({
    data: [
      {
        name: 'user1',
      },
      {
        name: 'user2',
      },
      {
        name: 'user3',
      },
    ],
  });
  1. Defining follows relationship
  const followUsers = await prisma.follows.createMany({
    data: [
      {
        followerId: 1,
        followingId: 2,
      },
      {
        followerId: 1,
        followingId: 3,
      },
      {
        followerId: 2,
        followingId: 3,
      },
    ],
  });
  1. To fetch who are the followers of user 1, it can be achieved through user model as well as follows model as described below:
  const findFollowersThroughUser = await prisma.socialUser.findMany({
    where: {
      following: {
        some: {
          followerId: 1,
        },
      },
    },
  });

  console.log('findFollowersThroughUser', findFollowersThroughUser);

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

  console.log('findFollowersThroughFollow', findFollowersThroughFollow);

Here's the output:

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

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

For updating the relations when someone unfollows, the record needs to be explicitly removed from the follows table in this case.

  • Related