GORM关联查询
Posted yzg-14
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了GORM关联查询相关的知识,希望对你有一定的参考价值。
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" }
以上是关于GORM关联查询的主要内容,如果未能解决你的问题,请参考以下文章