Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > golang gorm测试get请求查询

golang gorm实现get请求查询案例测试

作者:Jeff的技术栈

这篇文章主要为大家介绍了golang gorm实现get请求查询案例测试,

案例

package main
import (
   _ "github.com/go-sql-driver/mysql"
   "github.com/jinzhu/gorm"
   "github.com/gin-gonic/gin"
)
//班级-学生:一对多
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_Teacher;"` //一个学生有多个老师
}
type IDCard struct {
   gorm.Model
   StudentID uint  //一张卡只属于一个学生
   Money int  //卡里余额
}
//老师-学生:多对多
type Teacher struct {
   gorm.Model
   TeacherName string
   Students []Student `gorm:"many2many:Student_Teacher;"` //老师教多个学生
}
func main() {
   db, _ := gorm.Open("mysql", "root:admin123@/beego_test?charset=utf8&parseTime=True&loc=Local")
   db.AutoMigrate(&Class{},&Student{},&IDCard{},Teacher{})
   defer db.Close()
   // 测试数据
   //i := IDCard{
   // Money:99,
   //}
   //s := Student{
   // StudentName:"chary",
   // IDCard : i,
   //}
   //c := Class{
   // ClassName:"超神学院",
   // Students: []Student{s},
   //}
   //t := Teacher{
   // TeacherName:"雅典啦老师",
   // Students: []Student{s},
   //}
   //
   //_ = db.Create(&c).Error
   //_ = db.Create(&t).Error
   r:=gin.Default()
   r.POST("/student", func(c *gin.Context) {
       var student Student
       _ = c.BindJSON(&student)
       db.Create(&student)
   })
   r.GET("/student/:ID", func(c *gin.Context) {
      id := c.Param("ID")
      var student Student
      _ = c.BindJSON(&student)
      db.Preload("Teachers").Preload("IDCard").First(&student,"id=?",id)
      c.JSON(200,gin.H{
         "msg":student,
      })
   })
   r.GET("/class/:ID", func(c *gin.Context) {
      id := c.Param("ID")
      var class Class
      _ = c.BindJSON(&class)
      db.Preload("Students").Preload("Students.Teachers").First(&class,"id=?",id)

      c.JSON(200,gin.H{
         "msg":class,
      })
   })
   _ = r.Run(":8080")
}

查询班级get请求

查询学生get请求

以上就是golang gorm实现get请求查询案例测试的详细内容,更多关于golang gorm测试get请求查询的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文