How to realize get request query by golang gorm
Today, the editor will share with you the relevant knowledge points about how to achieve get request query by golang gorm. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
Case package mainimport (_ "github.com/go-sql-driver/mysql"github.com/jinzhu/gorm"github.com/gin-gonic/gin") / / Class-Student: one-to-many type Class struct {gorm.Model ClassName string Students [] Student / / Class has multiple students} / / Student-Student Card: one-to-one type Student struct {gorm.Model StudentName string ClassID uint / / Student belongs to one Each class IDCard IDCard / / one student has only one student card Teachers [] Teacher `gorm: "many2many:Student_Teacher "`/ / A student has multiple teachers} type IDCard struct {gorm.Model StudentID uint / / A card belongs to only one student Money int / / balance in the card} / / teacher-student: many-to-many type Teacher struct {gorm.Model TeacherName string Students [] Student `gorm:" many2many:Student_Teacher "`/ / teacher teaches multiple students} 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 () / / Test data / / I: = IDCard {/ / Money:99 / /} / / s: = Student {/ / StudentName: "chary", / / IDCard: I, / /} / c: = Class {/ / ClassName: "Super Theological Seminary", / / Students: [] Student {s}, / /} / t: = Teacher {/ / TeacherName: "Athens teacher", / / 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 msg {"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 (200djin.H {"msg": class,})) _ = r.Run (": 8080")} query class get request
Query student get request
These are all the contents of the article "how to implement get request query by golang gorm". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.