'How to query/update a self-relation in Prisma?
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.
Solution 1:[1]
Consider this example:
- Creating a user:
const createUsers = await prisma.user.createMany({
data: [
{
name: 'user1',
},
{
name: 'user2',
},
{
name: 'user3',
},
],
});
- Defining follows relationship
const followUsers = await prisma.follows.createMany({
data: [
{
followerId: 1,
followingId: 2,
},
{
followerId: 1,
followingId: 3,
},
{
followerId: 2,
followingId: 3,
},
],
});
- 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nurul Sundarani |
