Gin中使用GORM实现表关联查询-多对多
Gin中使用GORM实现表关联查询-多对多B站视频详解(第72讲): https://www.bilibili.com/video/BV1Rm421N7Jy
下面我们根据详细的示例来对Gin中使用GORM实现表关联查询-多对多进行详细的讲解。
1、定义学生 课程 学生课程表 model
如果想根据课程获取选学本门课程的学生,这个时候就在 Lesson 里面关联 Student
Lesson
package models
type Lesson struct {
Id int `json:"id"` Name string `json:"name"` Student []*Student `gorm:"many2many:lesson_student"` }
func (Lesson) TableName() string {
return "lesson"
}
Student
package models
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"
}
LessonStudent
package models
type LessonStudent struct {
LessonId int
StudentId int
}
func (LessonStudent) TableName() string {
return "lesson_student"
}
2、获取学生信息 以及课程信息
studentList := []models.Student{}
models.DB.Find(&studentList)
c.JSON(http.StatusOK, studentList)
lessonList := []models.Lesson{}
models.DB.Find(&lessonList)
c.JSON(http.StatusOK, lessonList)
3、查询学生信息的时候获取学生的选课信息
studentList := []models.Student{}
models.DB.Preload("Lesson").Find(&studentList)
c.JSON(http.StatusOK, studentList)
4、查询张三选修了哪些课程
studentList := []models.Student{}
models.DB.Preload("Lesson").Where("id=1").Find(&studentList)
c.JSON(http.StatusOK, studentList)
5、课程被哪些学生选修了
lessonList := []models.Lesson{}
models.DB.Preload("Student").Find(&lessonList)
c.JSON(http.StatusOK, lessonList)
6、计算机网络被那些学生选修了
lessonList := []models.Lesson{}
models.DB.Preload("Student").Where("id=1").Find(&lessonList)
c.JSON(http.StatusOK, lessonList)
7、查询数据指定条件
lessonList := []models.Lesson{}
models.DB.Preload("Student").Offset(1).Limit(2).Find(&lessonList)
c.JSON(http.StatusOK, lessonList)
8、关联查询指定子集的筛选条件
https://gorm.io/zh_CN/docs/preload.html 张三被开除了 查询课程被哪些学生选修的时候要去掉张三 用法:
access := []models.Access{}
models.DB.Preload("AccessItem", "status=1").Order("sort desc").Where("module_id=?", 0).Fin
d(&access)
lessonList := []models.Lesson{}
models.DB.Preload("Student", "id!=1").Find(&lessonList)
c.JSON(http.StatusOK, lessonList)
lessonList := []models.Lesson{}
models.DB.Preload("Student", "id not in (1,2)").Find(&lessonList)
c.JSON(http.StatusOK, lessonList)
9、自定义预加载 SQL
查看课程被哪些学生选修 要求:学生 id 倒叙输出 https://gorm.io/zh_CN/docs/preload.html 注意:需要引入 gorm.io/gorm 这个包
lessonList := []models.Lesson{}
models.DB.Preload("Student", func(db *gorm.DB) *gorm.DB {
return models.DB.Order("id DESC")
}).Find(&lessonList)
c.JSON(http.StatusOK, lessonList)
lessonList := []models.Lesson{}
models.DB.Preload("Student", func(db *gorm.DB) *gorm.DB {
return models.DB.Order("id DESC")
}).Find(&lessonList)
c.JSON(http.StatusOK, lessonList)