如何在gorm中创建双向many2many关系
时间:2023-04-13
浏览:127
作者:佚名
本篇文章向大家介绍《如何在gorm中创建双向many2many关系》,主要包括golang,具有一定的参考价值,需要的朋友可以参考一下。
问题内容
根据[文档](https://gorm.io/docs/many_to_many.html#Self-Referential-
Many2Many)自我关系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"`
}
今天带大家了解了golang的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
11.29
11.29
11.29
11.29
11.29
热门专题
