ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
> 本章介绍多对多关系(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 } ~~~