// User has and belongs to many languages, `user_languages` is the join table type User struct { gorm.Model Languages []Language `gorm:"many2many:user_languages;"` }
type Language struct { gorm.Model Name string }
当使用 GORM AutoMigrate 为 User 创建表时,GORM 会自动创建连接表
反向引用
声明
// User has and belongs to many languages, use `user_languages` as join table type User struct { gorm.Model Languages []*Language `gorm:"many2many:user_languages;"` }
type Language struct { gorm.Model Name string Users []*User `gorm:"many2many:user_languages;"` }
检索
// Retrieve user list with eager loading languages funcGetAllUsers(db *gorm.DB) ([]User, error) { var users []User err := db.Model(&User{}).Preload("Languages").Find(&users).Error return users, err }
// Retrieve language list with eager loading users funcGetAllLanguages(db *gorm.DB) ([]Language, error) { var languages []Language err := db.Model(&Language{}).Preload("Users").Find(&languages).Error return languages, err }
覆盖外键
对于 多对多 关系,连接表拥有引用两个模型的外键,例如
type User struct { gorm.Model Languages []Language `gorm:"many2many:user_languages;"` }
// Change model Person's field Addresses' join table to PersonAddress // PersonAddress must defined all required foreign keys or it will raise error err := db.SetupJoinTable(&Person{}, "Addresses", &PersonAddress{})