开发者

How to implement followers for users, as in twitter

I have a social network that I am making using php and mysql. I am trying to figure out how to make followers fo开发者_StackOverflowr each user. Should I create a table in mysql with a list of followers for each person, and create a table for everybody they follow? How should this work? How should I set up my data structures? Please help.


Table `followers`

id
user_id
follows_id

If a user follows another, add their ids to this table where user_id is the user that follows and follows_id is the user he's following.


You should look into ERD. You are right though. You have a table with users. Users have a many-to-many relationship with users, so create a table that contains that relation. It should have at least two fields; "user" and "follower", and you store the id's of the respective entities.


This certainly is a many to many relationship and i would use a composite primary key.

Instead of using an explicit id column i would make the combined columns of user_id and follower_id the primary key for the followers table. This would avoid any entries from being duplicated.

Also i have added a foreign key constraint so that if the user is deleted in the users table then all the users entries will be deleted from the the followers table;

create table followers
(
     user_id int unsigned not null, 
     follower_id int unsigned not null, 
     primary key(user_id,follower_id), 
     foreign key(user_id) references users(id) on delete cascade on update cascade
);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜