Followers/following database structure

后端 未结 4 2000
臣服心动
臣服心动 2021-01-31 05:52

My website has a followers/following system (like Twitter\'s). My dilemma is creating the database structure to handle who\'s following who.

What I came up with was crea

4条回答
  •  独厮守ぢ
    2021-01-31 06:38

    One weakness of that representation is that each relationship is encoded twice: once in the row for the follower and once in the row for the following user, making it harder to maintain data integrity and updates tedious.

    I would make one table for users and one table for relationships. The relationship table would look like:

    id | follower | following
    1  | 23       | 20
    2  | 58       | 20
    3  | 84       | 20
    4  | 20       | 11
    ...
    

    This way adding new relationships is simply an insert, and removing relationships is a delete. It's also much easier to roll up the counts to determine how many followers a given user has.

提交回复
热议问题