一对一
conf
appname = beegogorm httpport = 8080 runmode = dev mysqladmin="root" mysqlpwd="123456" mysqldb="itying"
models
core.go
package models import ( "github.com/astaxie/beego" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) var DB *gorm.DB var err error func init() { mysqladmin := beego.AppConfig.String("mysqladmin") mysqlpwd := beego.AppConfig.String("mysqlpwd") mysqldb := beego.AppConfig.String("mysqldb") //和数据库建立连接 // DB, err = gorm.Open("mysql", "root:123456@/beego?charset=utf8&parseTime=True&loc=Local") DB, err = gorm.Open("mysql", mysqladmin+":"+mysqlpwd+"@/"+mysqldb+"?charset=utf8&parseTime=True&loc=Local") DB.LogMode(true) //开启sql日志 if err != nil { beego.Error() } }
article.go
package models import ( _ "github.com/jinzhu/gorm" ) type Article struct { Id int `json:"id"` Title string `json:"title"` CateId string `json:"cate_id"` State int `json:"state"` ArticleCate ArticleCate `gorm:"foreignkey:Id;association_foreignkey:CateId"` } func (Article) TableName() string { return "article" }
多对一/多对一
articleCate.go
package models import ( _ "github.com/jinzhu/gorm" ) type ArticleCate struct { Id int `json:"id"` Title string `json:"title"` State int `json:"state"` Article []Article `gorm:"foreignkey:CateId;association_foreignkey:Id"` } func (ArticleCate) TableName() string { return "article_cate" }
controllers
package controllers import ( "beegogorm/models" "github.com/astaxie/beego" ) type ArticleController struct { beego.Controller } func (c *ArticleController) Get() { //1、查询文章信息 article := []models.Article{} models.DB.Find(&article) //2、查询文章信息的时候关联文章分类 (1对1--》文章 对 文章分类) article := []models.Article{} models.DB.Preload("ArticleCate").Find(&article) // 3、查询文章分类信息的时候关联文章 (1对多--》文章分类 对 文章) articleCate := []models.ArticleCate{} models.DB.Preload("Article").Find(&articleCate) // 一对多和一多一写法一样的 // 4、查询文章分类信息的时候关联文章 条件判断 articleCate := []models.ArticleCate{} models.DB.Preload("Article").Where("id>1").Find(&articleCate) articleCate := []models.ArticleCate{} models.DB.Preload("Article", "id>3").Where("id>1").Find(&articleCate) c.Data["json"] = articleCate c.ServeJSON() }
多对多
一个学生选修多门课程
一个课程也可以被多个学生选修
需要第三张表
models
lesson.go 课程表
package models import ( _ "github.com/jinzhu/gorm" ) type Lesson struct { Id int `json:"id"` Name string `json:"name"` Student []Student `gorm:"many2many:lesson_student;"` } func (Lesson) TableName() string { return "lesson" }
student.go 学生表
package models import ( _ "github.com/jinzhu/gorm" ) type Student struct { Id int Number string Password string ClassId int Name string Lesson []Lesson `gorm:"many2many:lesson_student;"` } func (Student) TableName() string { return "student" }
lessonStudent.go 关联表
package models import ( _ "github.com/jinzhu/gorm" ) type LessonStudent struct { LessonId int `json:"lesson_id"` StudentId int `json:"student_id"` } func (LessonStudent) TableName() string { return "lesson_student" }