爱摸鱼的Demon
首页
前端知识
后端技术
工程实践
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

爱摸鱼的Demon

我的地盘,欢迎光临。
首页
前端知识
后端技术
工程实践
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • C#

  • Golang

    • Go

    • Gin

    • GORM

      • Gorm初始化
      • Gorm之增删改查
      • Gorm之查询进阶版
      • Gorm之根据外键关联表
      • Gorm之关联进阶版
        • 1、查询student信息时获取lesson课信息
        • 2、查询lesson被哪些student选修了
        • 3、去掉某一个student信息的lesson
      • Gorm之事务
  • 后端技术
  • Golang
  • GORM
DemonW-X
2025-11-13
目录

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

# 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、查询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

# 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
编辑 (opens new window)
Gorm之根据外键关联表
Gorm之事务

← Gorm之根据外键关联表 Gorm之事务→

最近更新
01
Gorm之事务
11-13
02
Gorm之根据外键关联表
11-13
03
Gorm之查询进阶版
11-13
更多文章>
Theme by Vdoing | Copyright © 2022-2025 爱摸鱼的Demon | 桂ICP备2024034950号 | 桂公网安备45142202000030
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式