[Go实战]go-gorm的预加载 preload或related方法使用场景

特殊说明:

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连表查询

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值