多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
> 本章介绍一对一关系(has one) [TOC] ## 一对一关系(has one) ~~~ // User 包含一个 CreditCard, UserID 为外键 type User struct { gorm.Model CreditCard CreditCard } type CreditCard struct { gorm.Model UserID uint Number string } var card CreditCard db.Model(&user).Related(&card, "CreditCard") //// SELECT * FROM credit_cards WHERE user_id = 123; // 123 is user's primary key // CreditCard是user的字段名称,这意味着获得user的CreditCard关系并将其填充到变量 // 如果字段名与变量的类型名相同,如上例所示,可以省略,如: db.Model(&user).Related(&card) ~~~ ## 指定外键 ~~~ type Profile struct { gorm.Model Name string UserRefer uint } type User struct { gorm.Model Profile Profile `gorm:"ForeignKey:UserRefer"` } ~~~ ## 指定外键和关联外键 ~~~ type Profile struct { gorm.Model Name string UserID uint } type User struct { gorm.Model Refer string Profile Profile `gorm:"ForeignKey:UserID;AssociationForeignKey:Refer"` } ~~~