Are possible to make db.Preload() in GORM to be Auto-preload?

Viewed 166

model.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

Output:

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

I don't really know how db.Preload() works. Why i should use db.Preload() to get "SecondData" every time i need do nested struct ? Are it's possible only use db.Row() or db.Table().Joins().Where().Find(), i mean's without db.Preload()?

1 Answers

If you want SecondData loaded every time when the First struct is loaded without using Preload, you might consider using hooks.

It might look something like this:

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

So, when you load the First data, the AfterFind hook should be triggered.

Related