我们在日常工作当中经常遇到一对一和一对多的关系,那么在gorm中我们是怎么使用的呢?听我细细道来。 首先我们定义email、user和mobile三张表,他们对应的结构体如下:
Email表
package models
type Email struct {
Model
Address string
UserId uint
}
Mobile表
package models
type Mobile struct {
Model
Address string `json:"address"`
UserId uint
}
user表
package models
type User struct {
Model
Name string
Age uint
Mobile Mobile
EmailSlice []Email
}
主程序
package main
import (
"ginLearn.com/models"
)
func main() {
db := models.DB()
user := models.User{}
user.ID = 1
mobile := models.Mobile{}
//一个人拥有一个手机号码
//SELECT * FROM `mobiles` WHERE `mobiles`.`deleted_at` IS NULL AND ((`user_id` = 1))
//我们手动指定了关联字段
//自定关联字段
db.Model(&user).Related(&mobile, "userId")
//自动关联
//db.Model(&user).Related(&mobile)
//一个人拥有多个邮箱
//一对多的情况要定义一个切片
var emailSlice []models.Email
//自定关联字段
// SELECT * FROM `emails` WHERE `emails`.`deleted_at` IS NULL AND ((`user_id` = 1))
db.Model(&user).Related(&emailSlice, "userId")
//自动关联
//db.Model(&user).Related(&emailSlice)
}
一对一和一对多的关系并不复杂,就像示例当中,我们只需要明确对应关系,gorm会自动给我们找到对应关系。这里需要强调一下一对多的使用。
//一对多的情况要定义一个切片
var emailSlice []models.Email
//自定关联字段
// SELECT * FROM `emails` WHERE `emails`.`deleted_at` IS NULL AND ((`user_id` = 1))
db.Model(&user).Related(&emailSlice, "userId")
一定不要忘记了,一对多返回的应该是个切片,如果你不传入切片,那么gorm会把把结果的最后一个值放进切片中给你返回!