GORM 多对多关系配置
GORM 支持多对多关系映射,本文介绍 many2many 的核心用法。
什么是多对多关系
多对多关系指多个模型实例相互关联,如学生与课程,一个学生可选多门课,一门课可被多个学生选。
many2many 配置
Go
type Student struct {
gorm.Model
Name string
Courses []Course `gorm:"many2many:student_courses;"` // 多对多
}
type Course struct {
gorm.Model
Title string
}
// GORM 自动创建中间表 student_courses
// 包含 student_id 和 course_id 两个外键
中间表自定义
Go
// 带额外字段的中间表
type StudentCourse struct {
StudentID uint `gorm:"primaryKey"`
CourseID uint `gorm:"primaryKey"`
Score int // 额外字段:成绩
Enrolled time.Time // 额外字段:选课时间
Student Student
Course Course
}
type Student struct {
gorm.Model
Name string
Courses []Course `gorm:"many2many:student_courses;joinForeignKey:StudentID"`
}
关联操作
创建关联
Go
// 创建并关联
student := Student{
Name: "张三",
Courses: []Course{
{Title: "数学"},
{Title: "物理"},
},
}
db.Create(&student)
// 追加关联
db.Model(&student).Association("Courses").Append([]Course{
{Title: "化学"},
})
查询与删除
Go
// 查询关联
db.Model(&student).Association("Courses").Find(&courses)
// 删除关联
db.Model(&student).Association("Courses").Delete(&course)
// 替换所有关联
db.Model(&student).Association("Courses").Replace([]Course{newCourse})
// 清空关联
db.Model(&student).Association("Courses").Clear()
多对多关系必须通过中间表实现,GORM 默认自动创建中间表。
注意事项
many2many标签值指定中间表名称,默认格式:模型A_模型B- 中间表主键为两个外键的复合主键
- 复杂中间表需手动定义模型,指定 joinForeignKey
- Association 操作自动处理中间表记录
要点总结
many2many实现多对多关系,自动创建中间表- 中间表默认复合主键,可自定义额外字段
- 使用 Association 方法管理关联关系
- 复杂场景需手动定义中间表模型
文章存放路径:D:\git2\jwdev\articles\GORM\进阶\关联关系管理\多对多关系配置.md
📝 发现内容有误?点击此处直接编辑