sqlgomany-to-manygo-gorm

How to create a bidirectional many2many relationship in gorm


According to the doc self-relational many2many is like below

type User struct {
  gorm.Model
  Friends []*User `gorm:"many2many:user_friends"`
}

But I want to be able to model something like this:

type User struct {
  gorm.Model
  Followings []*User `gorm:"many2many:user_relation"`
  Followers []*User `gorm:"many2many:user_relation"`
}

So the following process works well. If userA followed userB, then userB could see userA in its followers.


Solution

  • I was able to achieve it with these tags:

    type User struct {
      gorm.Model
      Followings []*User `gorm:"many2many:user_relation;foreignKey:ID;joinForeignKey:UserA;References:ID;joinReferences:UserB"`
      Followers []*User `gorm:"many2many:user_relation;foreignKey:ID;joinForeignKey:UserB;References:ID;joinReferences:UserA"`
    }