Home > Mobile >  constructing a followers/following relationship
constructing a followers/following relationship

Time:11-28

A relationship between users and followers is many-to-many.

My model:

type User struct {
    gorm.Model
    Username   string  `json:"username" gorm:"unique"`
    Name       string  `json:"name"`
    Followers  []*User `json:"followers" gorm:"many2many:user_followers"`
    Following  []*User `json:"following" gorm:"many2many:user_following"`
}

This model, when migrated, creates two junction tables which hold the user id and the follower/following id respectively.

Am I making a mistake by separating the Followers and Followings and in they are actually supposed to be just one table?

CodePudding user response:

I'd follow the KISS principle here and simplify the solution.

One table followers with user_from_id,user_to_id,create_at,... fields and with a (user_from_id,user_to_id) unique key should be enough. The (user_from_id,user_to_id) unique key will make sure that there are no duplicates.

Most likely you'll have 4 types of queries for this table:

  1. Select current user followers ... WHERE user_to_id=%current_user_id% ...
  2. Select users followed by the current user ... WHERE user_from_id=%current_user_id% ...
  3. Check if the current user is following another user: ... WHERE user_from_id=%current_user_id% AND user_to_id=%another_user_id% ...
  4. Check if another user is following the current user: ... WHERE user_from_id=%another_user_id% AND user_to_id=%current_user_id% ...

Cases 2,3,4 are already covered by the (user_from_id,user_to_id) unique key. However, you'll need an extra index (not unique, simple index will be enough) to optimise the 1st query: (user_to_id).

Note: you may need extra indexes to optimise queries for your table. I assumed the most common use cases.

  • Related