gorm的related理解和实例
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
var (
dev_db = "aplum:plum2016@tcp(localhost:3306)/aplum?charset=utf8"
local_db = "root:123456@tcp(localhost:3306)/test?charset=utf8"
)
type MyUser struct {
ID int `gorm:"TYPE:int(11);NOT NULL;PRIMARY_KEY;INDEX"`
Name string
}
type MyProfile struct {
ID int `gorm:"TYPE:int(11);NOT NULL;PRIMARY_KEY;INDEX"`
Name string
User MyUser `gorm:"foreignkey:UserRefer"`
UserRefer uint
}
func main() {
db, err := gorm.Open("mysql", local_db)
db.LogMode(true)
if err != nil {
panic(err)
}
defer db.Close()
related(db)
}
func setData(db *gorm.DB) {
db.Debug().AutoMigrate(&MyUser{})
db.Debug().AutoMigrate(&MyProfile{})
db.Debug().Create(&MyUser{ID: 1, Name: "uname1"})
db.Debug().Create(&MyUser{ID: 2, Name: "uname2"})
db.Debug().Create(&MyProfile{ID: 11, Name: "pname2", UserRefer: 1})
db.Debug().Create(&MyProfile{ID: 22, Name: "pname2", UserRefer: 2})
}
func related(db *gorm.DB) {
var profile MyProfile
db.Debug().First(&profile)
fmt.Println(fmt.Sprintf("%+v", profile))
db.Model(&profile).Related(&profile.User, "UserRefer")
fmt.Println(fmt.Sprintf("%+v", profile))
}
![](https://img2020.cnblogs.com/blog/900073/202004/900073-20200415152952230-1294967989.png)
gorm的tag foreignkey就是图中的 foreignkey,
tag ASSOCIATION_FOREIGNKEY 就是图中的references。
定义外健约束的2个关键字,翻译到gorm的用法就是gorm:"FOREIGNKEY:UserId;ASSOCIATION_FOREIGNKEY:ID"
。
![](https://img2020.cnblogs.com/blog/900073/202004/900073-20200415153017993-1362193397.png)
分类: 框架原理和源码
有如下结构:
type User struct {
gorm.Model
Name string
Company []Company
}
type Company struct {
gorm.Model
Job string
User User
UserID int
}
var user User
var company []Company
user.ID = 1
db.Model(&user).Related(&company)
db.Model(&user).Association("company").Find(&company)
使用Related和Association都可以查询出来关联的company的数据.那他们的差异是什么呢?### 题目描述
阅读 9.1k
2019-12-03
2019-12-03
二者区别在于谁主谁从
下述代码中user表是源,company关联源中的字段名,简而言之通过先查user-->commpany 最终的主表记录从user出发
db.Model(&user).Association("company").Find(&company)
而Related方法其内的company表是要查主表源,主查company表user实例只是条件填充对象
db.Model(&user).Related(&company) //// SELECT * FROM company WHERE user_id = 1; // 1 is user's primary key
开启sql打印一目了然
// 启用Logger,显示详细日志 db.LogMode(true)