gin 数据库关系
一对一关系
type IDCard struct {
gorm.Model
StudentID uint
Num int
}
type Student struct {
gorm.Model
IDCard IDCard
StudentName string
}
一对多关系
type Class struct {
gorm.Model
ClassName string
Students []Student
}
type Student struct {
gorm.Model
StudentName string
ClassID uint
}
多对多关系
type Student struct {
gorm.Model
StudentName string
Teachers []Teacher `gorm:"many2many:student_teachers;"`
}
type Teacher struct {
gorm.Model
TeacherName string
Students []Student `gorm:"many2many:student_teachers;"`
}
定义表结构
type Class struct {
gorm.Model
ClassName string
Students []Student
}
type Student struct {
gorm.Model
StudentName string
ClassID uint
IDCard IDCard
Teachers []Teacher `gorm:"many2many:student_teachers;"`
}
type IDCard struct {
gorm.Model
StudentID uint
Num int
}
type Teacher struct {
gorm.Model
TeacherName string
Students []Student `gorm:"many2many:student_teachers;"`
}
type Page struct {
PageNum int `form:"page_num"`
PageSize int `form:"page_size"`
Keyword string `form:"keyword"`
Desc bool `form:"desc"`
}
type StudentResponse struct {
StudentName string
}
跨域请求
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin")
if origin != "" {
c.Header("Access-Control-Allow-Origin", "*") // 可将将 * 替换为指定的域名
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
}
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
c.Next()
}
}
链接数据库 创建数据表
func main() {
dsn := "root:alger@tcp(127.0.0.1:3306)/gosql?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open("mysql", dsn)
if err != nil {
fmt.Println(err)
panic(err)
}
db.AutoMigrate(&Teacher{}, &Class{}, &Student{}, &IDCard{})
defer db.Close()
}
启动服务 使用跨域中间件
r := gin.Default()
r.Use(Cors())
//r.POST...
r.Run(":8080")
请求的增删改查
//分页查询
r.GET("/student", func(ctx *gin.Context) {
var p Page
if ctx.ShouldBindQuery(&p) != nil {
ctx.JSON(http.StatusUnauthorized, gin.H{
"err_msg": "参数错误",
})
return
}
if p.PageNum 0 {
p.PageNum = 1
}
var students []Student
if err := db.Limit(p.PageSize).Offset((p.PageNum-1)*p.PageSize).Find(&students).Error; err != nil {
ctx.JSON(http.StatusUnauthorized, gin.H{
"err_msg": err.Error(),
})
}
var total int
db.Model(&Student{}).Count(&total)
pageNum := total / p.PageSize
if total % p.PageSize != 0{
pageNum++
}
ctx.JSON(http.StatusOK, gin.H{
"code":200,
"msg":"查询成功",
"data": students,
"total": total,
})
})
//id查询单个学生
r.GET("/student/:id", func(ctx *gin.Context) {
var student Student
id := ctx.Param("id")
db.Preload("Teachers").Preload("IDCard").First(&student, id)
ctx.JSON(http.StatusOK, student)
})
//修改学生
r.PUT("/student/:id", func(ctx *gin.Context) {
var student Student
id := ctx.Param("id")
db.First(&student, id)
ctx.BindJSON(&student)
db.Save(&student)
ctx.JSON(http.StatusOK, student)
})
//删除学生
r.DELETE("/student/:id", func(ctx *gin.Context) {
var student Student
id := ctx.Param("id")
db.First(&student, id)
db.Delete(&student)
ctx.JSON(http.StatusOK, gin.H{"id #" + id: "deleted"})
})
//指定返回数据
type StudentResponse struct {
StudentName string
}
r.GET("/student", func(ctx *gin.Context) {
// var students []Student
data := &[]*StudentResponse{}
db.Table("students").Find(&data)
ctx.JSON(http.StatusOK, data)
})
版权声明:
作者:89391311
链接:https://www.csev.cn/code-2/golang/20241203536.html
来源:彩色动力-测试分享
版权声明:本文欢迎任何形式转载,转载时完整保留本声明信息(包含原文链接、原文出处、原文作者、版权声明)即可。本文后续所有修改都会第一时间在原始地址更新。
作者:89391311
链接:https://www.csev.cn/code-2/golang/20241203536.html
来源:彩色动力-测试分享
版权声明:本文欢迎任何形式转载,转载时完整保留本声明信息(包含原文链接、原文出处、原文作者、版权声明)即可。本文后续所有修改都会第一时间在原始地址更新。
THE END
二维码
打赏
文章目录
关闭
共有 0 条评论