栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

GORM v2 一对一关联查询使用(Belongs To 、Has One)

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

GORM v2 一对一关联查询使用(Belongs To 、Has One)

GORM v1 和 v2区别

一定要区分好,不然会导致相关功能无法使用

GORM v1

项目:https://github.com/jinzhu/gorm

文档:https://gorm.io/docs/

GORM v2

项目:https://github.com/go-gorm/gorm

文档:GORM Guides | GORM - The fantastic ORM library for Golang, aims to be developer friendly.

前言

说明:一个学生(students)拥有一条信息(information);相应的,一条信息(information)属于对应的一个学生(students)

表结构 students表
CREATE TABLE `students` (
    `id` INT ( 11 ) NOT NULL AUTO_INCREMENT,
    `name` VARCHAr ( 64 ) DEFAULT NULL,
    PRIMARY KEY ( `id` )
) ENGINE = MyISAM AUTO_INCREMENT = 2 DEFAULT CHARSET = utf8mb4;

  

information表
CREATE TABLE `information` (
   `id` INT ( 11 ) NOT NULL AUTO_INCREMENT COMMENT '信息表',
   `student_id` INT ( 11 ) DEFAULT NULL,
   `sex` TINYINT ( 1 ) DEFAULT NULL,
   `age` INT ( 4 ) DEFAULT NULL,
   `hometown` VARCHAr ( 128 ) DEFAULT NULL,
   PRIMARY KEY ( `id` )
) ENGINE = MyISAM AUTO_INCREMENT = 3 DEFAULT CHARSET = utf8mb4;

测试数据

Belong To

说明:一条信息属于一个学生,信息是查询主体

student模型
package models

type Student struct {
	ID int64 `gorm:"primary_key"`
	Name string
}

information模型
package models

type Information struct {
	ID int64 `gorm:"primary_key"`
	StudentID int64
	Sex uint8
	Age uint8
	HT string `gorm:"column:hometown"`
	Student Student `gorm:"foreignKey:student_id"`
}

执行查询
information := new (models.Information)

db.Preload("Student").First(&information)
// db.Joins("Student").First(&information)

fmt.Println(information)

Has One

说明:学生有一条信息,学生是查询主体

student模型
package models

type Student struct {
	ID int64 `gorm:"primary_key"`
	Name string
	Info Information `gorm:"foreignKey:student_id"`
}

information模型
package models

type Information struct {
	ID int64 `gorm:"primary_key"`
	StudentID int64
	Sex uint8
	Age uint8
	HT string `gorm:"column:hometown"`
}

 执行查询
student := new (models.Student)

db.Preload("Info").First(&student)
// db.Joins("Info").First(&student)

fmt.Println(student)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/990561.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号