是否可以使 GORM 中的 db.Preload() 成为自动预加载?

sky*_*cyr 6 go go-gorm

模型.go:


type First struct {
    ID            int     `json:"id" gorm:"column:id;primary_key"`
    Status        string  `json:"status" gorm:"column:status"`
    SecondID      int     `json:"second_id" gorm:"column:second_id"`
    SecondData    Second  `json:"second_data" gorm:"foreignKey:SecondID;references:ID"`
}

type Second struct {
    ID            int     `json:"id" gorm:"column:second_id;primary_key"`
    Status        string  `json:"status" gorm:"column:status"`
    Description   string  `json:"description" gorm:"column:description"`
}

var res []model.First

db.Raw("first.*, second.* FROM first LEFT JOIN second ON first.second_id = second.second_id")
db.Preload("SecondData").Find(&res).Error

Run Code Online (Sandbox Code Playgroud)

输出:

{
    "id": 1,
    "status": "A",
    "second_id": 1
    "second_data": {
        "id": 1
        "status": "B",
        "description": "blablabla"
    }
}

Run Code Online (Sandbox Code Playgroud)

我真的不知道 db.Preload() 是如何工作的。为什么每次我需要做嵌套结构时我都应该使用 db.Preload() 来获取“SecondData”?是否可以只使用 db.Row() 或 db.Table().Joins().Where().Find(),我的意思是没有 db.Preload()?

Emi*_*vic 3

如果您希望SecondData每次加载First结构体时都加载而不使用 using Preload,您可以考虑使用hooks

它可能看起来像这样:

func (f *First) AfterFind(tx *gorm.DB) error {
  return tx.First(&f.SecondData, f.SecondID).Error
}
Run Code Online (Sandbox Code Playgroud)

因此,当您加载First数据时,AfterFind应该触发挂钩。