特殊说明:

gorm官方文档对foreign key 有这么一句话:To define a belongs to relationship, the foreign key must exists, default foreign key uses owner’s type name plus its primary key(要定义属于关系,外键必须存在,默认外键使用所有者的类型名及其主键)也就是说默认外键满足其所有者的类型名和主键

package main
import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
// 文章
type Topics struct {
	Id         int        `gorm:"primary_key"`
	Title      string     `gorm:"not null"`
	UserId     int        `gorm:"not null"`
	CategoryId int        `gorm:"not null"`
	Category   Categories `gorm:"foreignkey:CategoryId"` //文章所属分类外键
	User       Users      `gorm:"foreignkey:UserId"`     //文章所属用户外键
// 用户
type Users struct {
	Id   int    `gorm:"primary_key"`
	Name string `gorm:"not null"`
// 分类
type Categories struct {
	Id   int    `gorm:"primary_key"`
	Name string `gorm:"not null"`
func GetDB() *gorm.DB {
	db, err := gorm.Open("postgres", "postgres://postgres:root@localhost:5432/test?sslmode=disable")
	if err != nil {
		fmt.Println("db error:", err)
	} else {
		fmt.Println("database connection success")
	//defer db.Close()
	return db
func main() {
	db := GetDB()
	models := []interface{}{
		&Topics{},
		&Users{},
		&Categories{},
	//1.执行建表语句
	err := db.Debug().AutoMigrate(models...).Error
	if err != nil {
		fmt.Println("db error:", err)
	//2.执行sql
	//INSERT INTO topics("id", "title", "user_id", "category_id") VALUES (1, '测试', 1, 1);
	//INSERT INTO categories("id", "name") VALUES (1, '测试分类');
	//INSERT INTO users("id", "name") VALUES (1, '测试用户');
	//3.执行预加载
	topics, err := GetTopicsById(db, 1)
	if err != nil {
		fmt.Println("get topics error:", err)
	fmt.Println(topics)
func GetTopicsById(db *gorm.DB, id int) (*Topics, error) {
	var topic Topics
	//查询方法1
	//err := db.Model(&topic).Where("id=?", id).First(&topic).
	//	Related(&topic.Category, "CategoryId").
	//	Related(&topic.User, "UserId").Error
	//查询方法2
	err := db.Where("id=?", id).
		Preload("Category").
		Preload("User").
		First(&topic).Error
	if err != nil {
		return nil, err
	return &topic, nil

参考文章:

gorm 连接查询(两表联查,三表联查)预加载的坑_丁涛的博客-CSDN博客_gorm连表查询

分类:
后端
标签: