phpmysqlsocial-mediasocial-network-friendship

PHP/MYSQL/social network best pracice table structure for followers


I would like to allow users to follow other users as with Twitter, Instagram etc. Am thinking that this should include table structure something like following:

Users with userid, password, email, fname, lname

Followers with userid1(INT), followstatus(TINYINT), usererid2 (INT)

New row is created when user1 decides to follow user2. Later follow status can be turned off if user1 decides to no longer follow user2. There would be a separate entry if user2 follows user 1

I can tell user1 whom he is following with query to this table. And tell users how many people are following them with count query. Then conditional on this relationship, print out info on user2s actions (followee) to user1 (follower).

Is that best practice? Or is there more to it.... Are there other fields, tables required?

Note: users have another table of people, not necessarily users but I'm thinking follower status should be in separate table.


Solution

  • That looks good. One note, though: if your project will really take off, you'll soon grow out of a single machine and will have to shard. That means breaking your user and relation tables into smaller ones. It's a big topic and out of scope here.

    Once you break them, a certain type of queries becomes difficult or impossible.

    For example, now it is simple to query "who follows me".

    select * from followers where user2 = me;
    

    or "whom do I follow?"

    select * from followers where user1 = me;
    

    Once you break the followers table, one of these queries will be impossible (because the data may span multiple tables/databases/servers). To overcome this, you might want to create two tables:

    i_follow (user1 int, user2 int)
    follow_me (user1 int, user2 int)
    

    and insert corresponding records on each new relation.

    This is just tip of the iceberg. Embark on this journey and you'll find many interesting problems to solve :)