比如说,你的应用包含 User 和 Language,一个 User 可以说多种 Language,多个 User 也可以说一种 Language。
// User 拥有并属于多种 Language,使用 `user_languages` 连接表 type User struct { gorm.Model Languages []Language `gorm:"many2many:user_languages;"` }
type Language struct { gorm.Model Name string }
互引用关联
// User 拥有并属于多种 Language,使用 `user_languages` 连接表 type User struct { gorm.Model Languages []*Language `gorm:"many2many:user_languages;"` }
type Language struct { gorm.Model Name string Users []*User `gorm:"many2many:user_languages;"` }
var users []User language := Language{}
db.First(&language, "id = ?", 111)
db.Model(&language).Related(&users, "Users") //// SELECT * FROM "users" INNER JOIN "user_languages" ON "user_languages"."user_id" = "users"."id" WHERE ("user_languages"."language_id" IN ('111'))
多外键
type CustomizePerson struct { IdPerson string`gorm:"primary_key:true"` Accounts []CustomizeAccount `gorm:"many2many:PersonAccount;association_foreignkey:idAccount;foreignkey:idPerson"` }
type CustomizeAccount struct { IdAccount string`gorm:"primary_key:true"` Name string }