今天小编给大家分享一下golang gorm怎么实现get请求查询的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
案例
package mainimport ( _ "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请求查询”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注编程网行业资讯频道。