Bootstrap

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)

;