ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
> 本章介绍一对多关系(has many) [TOC] ## 一对多关系(has many) ~~~ // User 包含多个 emails, UserID 为外键 type User struct { gorm.Model Emails []Email } type Email struct { gorm.Model Email string UserID uint } db.Model(&user).Related(&emails) // SELECT * FROM emails WHERE user_id = 111; // 111 是 user 的主键 ~~~ ## 指定外键 ~~~ type Profile struct { gorm.Model Name string UserRefer uint } type User struct { gorm.Model Profiles []Profile `gorm:"ForeignKey:UserRefer"` } ~~~ ## 指定外键和关联外键 ~~~ type Profile struct { gorm.Model Name string UserID uint } type User struct { gorm.Model Refer string Profiles []Profile `gorm:"ForeignKey:UserID;AssociationForeignKey:Refer"` } ~~~