I am designing a database schema for a social network
and need to implement mutual friend relationships between users in a database.
But what is the best way to represent such a relationship in the database? Is it even possible?
As an example, I will take a sample from Prisma.
The follower relationship is implemented there like this, although it doesn't guarantee reciprocity:
CREATE TABLE "User" (
id integer DEFAULT nextval('"User_id_seq"'::regclass) PRIMARY KEY,
name text
);
CREATE TABLE "_UserFollows" (
"A" integer NOT NULL REFERENCES "User"(id) ON DELETE CASCADE ON UPDATE CASCADE,
"B" integer NOT NULL REFERENCES "User"(id) ON DELETE CASCADE ON UPDATE CASCADE
);
model User {
id Int @id @default(autoincrement())
name String?
followedBy Follows[] @relation("following")
following Follows[] @relation("follower")
}
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])
}
How can I ensure data integrity and atomicity of changes? Additionally, how can I make sure that when a relationship is deleted from one side, the relationship from the other side is also deleted?