Skip to content

关联

1对1

  • 例如:1个学生 只有详细信息表
go
type Student struct {
	No      string      `gorm:"primary_key;not null;size:16;comment:学号"`
    ClassNo string      `gorm:"not null;size:16;comment:班级编号"`
	Name    string      `gorm:"not null;size:10"`
	Age     int         `gorm:"not null;size:10"`
	Gender  int         `gorm:"not null;size:1"`
    //foreignKey 关联表的字段  references本表的字段
	Info   StudentInfo `gorm:"foreignKey:StuNo;references:No"`
}

type StudentInfo struct {
	StuNo   string `gorm:"primary_key;not null;size:16;comment:学号"`
	IdCard1 string `gorm:"not null;comment:国徽面"`
	IdCard2 string `gorm:"not null;comment:头像面"`
	Address string `gorm:"not null"`
}

1对多

  • 例如:1个班级 有多个学生
go
type Class struct {
	ClassNo string    `gorm:"primary_key;not null;size:16;comment:班级编号"`
	Name    string    `gorm:"not null;comment:班级名"`
    //foreignKey 关联表的字段  references本表的字段
	StuList []Student `gorm:"foreignKey:ClassNo;references:ClassNo"`
}

type Student struct {
	No      string      `gorm:"primary_key;not null;size:16;comment:学号"`
	ClassNo string      `gorm:"not null;size:16;comment:班级编号"`
	Name    string      `gorm:"not null;size:10"`
	Age     int         `gorm:"not null;size:10"`
	Gender  int         `gorm:"not null;size:1"`
	Info    StudentInfo `gorm:"foreignKey:StuNo;references:No"`
}

type StudentInfo struct {
	StuNo   string `gorm:"primary_key;not null;size:16;comment:学号"`
	IdCard1 string `gorm:"not null;comment:国徽面"`
	IdCard2 string `gorm:"not null;comment:头像面"`
	Address string `gorm:"not null"`
}