根据the doc的自相关many2many
如下
type User struct {
gorm.Model
Friends []*User `gorm:"many2many:user_friends"`
}
但我希望能够建模如下:type User struct {
gorm.Model
Followings []*User `gorm:"many2many:user_relation"`
Followers []*User `gorm:"many2many:user_relation"`
}
因此,以下过程运行良好。如果userA
跟在userB
之后,则userB
可以在其关注者中看到userA
。
最佳答案
我可以通过以下标签实现它:
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"`
}
关于sql - 如何在gorm中创建双向多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63782715/