数据库三个,如下:
注意:配置中间表的时候,表设计层面最好和配置的其他两张表契合,例如其他两张表为fate内的master和slave;要整合其对应关系的话,设计中间表的结构为master_id和slave_id最好(不然会涉及重写外键的操作)
重写外键(介绍)
对于 many2many
关系,连接表会同时拥有两个模型的外键,例如:
type User struct {gorm.ModelLanguages []Language `gorm:"many2many:user_languages;"`
}type Language struct {gorm.ModelName string
}// 连接表:user_languages
// foreign key: user_id, reference: users.id
// foreign key: language_id, reference: languages.id
若要重写它们,可以使用标签 foreignKey
、references
、joinforeignKey
、joinReferences
。当然,您不需要使用全部的标签,你可以仅使用其中的一个重写部分的外键、引用。
type User struct {gorm.ModelProfiles []Profile `gorm:"many2many:user_profiles;foreignKey:Refer;joinForeignKey:UserReferID;References:UserRefer;joinReferences:ProfileRefer"`Refer uint `gorm:"index:,unique"`
}type Profile struct {gorm.ModelName stringUserRefer uint `gorm:"index:,unique"`
}// 会创建连接表:user_profiles
// foreign key: user_refer_id, reference: users.refer
// foreign key: profile_refer, reference: profiles.user_refer
Many To Many | GORM - The fantastic ORM library for Golang, aims to be developer friendly.https://gorm.io/zh_CN/docs/many_to_many.html
前期准备工作:
1、创建要操作表的models:
/models/lesson.go:
package modelstype Lesson struct {Id int `json:"id"`Name string `json:"name"`}func (Lesson) TableName() string {return "lesson"
}
/models/student.go:
package modelstype Student struct {Id intNumber stringPassword stringClassId intName string}func (Student) TableName() string {return "student"
}
/models/lessonStudent.go:
package modelstype LessonStudent struct {LessonId int `json:"lesson_id"`StudentId int `json:"student_id"`
}func (LessonStudent) TableName() string {return "lesson_student"
}
2、路由创建:
package routersimport ("gindemo04/controllers/admin""gindemo04/middle""github.com/gin-gonic/gin"
)func AdminRoutersInit(r *gin.Engine) {//middlewares.InitMiddleware中间件adminRouters := r.Group("/admin", middle.InitMiddleware){adminRouters.GET("/student", admin.StudentController{}.Index)}
}