🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
> 本章介绍多对多关系(many to many) [TOC] ## 多对多关系(many to many) ~~~ // User 包含并属于多个 languages, 使用 `user_languages` 表连接 type User struct { gorm.Model Languages []Language `gorm:"many2many:user_languages;"` } type Language struct { gorm.Model Name string } db.Model(&user).Related(&languages, "Languages") // SELECT * FROM "languages" INNER JOIN "user_languages" ON "user_languages"."language_id" = "languages"."id" WHERE "user_languages"."user_id" = 111 ~~~ ## 指定外键 ~~~ type CustomizePerson struct { IdPerson string `gorm:"primary_key:true"` Accounts []CustomizeAccount `gorm:"many2many:PersonAccount;ForeignKey:IdPerson;AssociationForeignKey:IdAccount"` } type CustomizeAccount struct { IdAccount string `gorm:"primary_key:true"` Name string } ~~~