The heart of a social network
A social network seems complicated, but it boils down to three entities:
- Users: each person with their
idand theirname. - Followers: who follows whom.
- Posts: what each user writes.
The interesting piece is the followers one. Notice: a user can follow many others, and at the same time be followed by many. That is an N:M (many-to-many) relationship. But there is a special detail: both sides of the relationship are the same type of entity (a user follows another user).
A table with itself: the graph
When an entity relates to itself with N:M cardinality, what you get is a directed graph: the nodes are the users and the edges are the "follows". Direction matters: Ana following Beto does not imply that Beto follows Ana.
We model that relationship with a bridge table with two columns, both pointing to
users:
CREATE TABLE followers (
follower_id INTEGER, -- who follows
followed_id INTEGER -- whom they follow
);
Each row is an edge of the graph. To find out whom Ana
(id = 1) follows, you filter by follower_id = 1 and look at the followed_id.
What's coming
In the next exercises you will build, in order:
- the feed query (the posts of who you follow),
- the logic of the feed in JavaScript and the like toggle,
- a React component for a post with its "Like" button,
- and you will solve the N+1 problem when loading the authors.