I have a quick question ! Thank you in advance for...
# orm-help
e
I have a quick question ! Thank you in advance for any answer provided. I have a a model which is a User and it has a field called friends count. My question is it possible to have an automatic reference so that the count updates automatically when a friend deletes he’s account?
👀 1
t
do you reference friends in the user model? If so, you don’t need to make a count field. You can get the total count of related data here.
e
Hello Tyler, yes i do connect it. I read the docs about the count but I do understand it like you have to do a get request and then update the friends count. My point is that I have the relation friend and a specific field called friends count
It is possible to link the friends count to the number of relations ?
t
Can you post your User model here?
e
Yeah sure
model User {
uid                  Int      @id @default(autoincrement())
user_name String @unique
is_active Boolean @default(true)
friends_count Int @default(0)
friends              Friend[]
sent_friend_requests Friend[] @relation(name: "sender")
}
model Friend {
uid Int @id @default(autoincrement())
players    User[]
sender     User   @relation(name: "sender", fields: [sender_uid], references: [uid], onDelete: Cascade)
sender_uid String
status FriendRequestStatus @default(PENDING)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
t
Copy code
const user = await prisma.user.findUnique({
    where: {
      id: "a users id",
    },
    include: {
      _count: {
        select: {
          friends: true
        }
      }
    },
  });

  const friendCount = user._count.friends
you can do the above.
friendCount
will be the # of friends that particular user has. No need to manually update a counter yourself.
e
Great, thank you Tyler ! It works 🙂
fast parrot 1