亲宝软件园·资讯

展开

golang gorm测试get请求查询

Jeff的技术栈 人气:0

案例

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请求

加载全部内容

相关教程
猜你喜欢
用户评论