多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
> 本章介绍一对多关系(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"` } ~~~