gpt4 book ai didi

sql - 如何在gorm中创建双向多对多关系

转载 作者:行者123 更新时间:2023-12-01 21:09:24 25 4
gpt4 key购买 nike

根据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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com