Gorm之关联进阶版
有一个student表:

他与lesson表:

根据lessonstudent表关联:

他们仨的关联关系如图所示:

初始化表
//lesson.go
type Lesson struct {
Id int
Name string
Student []Student `gorm:"many2many:lesson_student;"` //many-to-many
}
func (Lesson) TableName() string {
return "lesson"
}
//lessonStudent.go
type LessonStudent struct {
LessonId int
StudentId int
}
func (LessonStudent) TableName() string {
return "lesson_student"
}
//student.go
type Student struct {
Id int
Number string
Password string
ClassId int
Name string
//Lesson []Lesson `gorm:"many2many:lesson_student;"`
}
func (Student) TableName() string {
return "student"
}
//controller.go
type StudentController struct {
BaseController
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 1、查询student信息时获取lesson课信息
func (con StudentController) Index(c *gin.Context) {
stuList := []models.Student{}
//查询学生信息时获取学生选修课信息
models.DB.Preload("Lesson").Find(&stuList)
c.JSON(http.StatusOK, gin.H{
"result": stuList,
})
}
func (con StudentController) Detail(c *gin.Context) {
//查询张三信息时获取张三选修课信息
stuList := []models.Student{}
models.DB.Preload("Lesson").Where("Name = ?", "张三").Find(&stuList)
c.JSON(http.StatusOK, gin.H{
"result": stuList,
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 2、查询lesson被哪些student选修了
func (con StudentController) LessonByStu(c *gin.Context) {
lessonList := []models.Lesson{}
//查询课程被哪些学生选修了
//models.DB.Preload("Student").Find(&lessonList)
//查询课程被哪些学生选修了(id倒叙)
models.DB.Preload("Student", func(db *gorm.DB) *gorm.DB { return db.Order("student.id desc") }).Find(&lessonList)
c.JSON(http.StatusOK, gin.H{
"result": lessonList,
})
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 3、去掉某一个student信息的lesson
func (con StudentController) LessonExcept(c *gin.Context) {
//张三被开除了,查询课程被哪些学生选修了(去掉张三)
lessonList := []models.Lesson{}
models.DB.Preload("Student", "id !=?", 1).Find(&lessonList)
c.JSON(http.StatusOK, gin.H{
"result": lessonList,
})
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
编辑 (opens new window)