简体   繁体   中英

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.

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 :)

I think you're on the right track. A table containing users is a must. The second table is what relates the followers to the followees. This will let you establish who follows who, allows relationships in both directions for any 2 users, and makes queries simple. Also, importantly, you're not storing any important information twice. Removal of a relationship is also easy with a single delete query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM