I am trying to auto-preload my models but am having difficulty doing so.
These are the models i am using :
package domain
type User struct {
gorm.Model
Name string
Car Car `gorm:"auto_preload"`
Account Account `gorm:"auto_preload"`
}
type Car struct {
gorm.Model
Type int
UserID uint
}
type Account struct {
gorm.Model
Powerlevel int
UserID uint
}
This is the code i am executing to test the auto-preloading feature:
func main() {
db, err := gorm.Open("sqlite3", "./data.db")
if err != nil {
println(err.Error())
}
//Migrate the tables
db.AutoMigrate(&domain.User{})
db.AutoMigrate(&domain.Car{})
db.AutoMigrate(&domain.Account{})
// Initialize our models
var testUser domain.User
var car = domain.Car{Type: 1994}
var account = domain.Account{Powerlevel: 9001}
testUser.Name = "Jim Bob"
testUser.Car = car
testUser.Account = account
// Save the user
db.Create(&testUser)
// Get a new user
var newUser domain.User
db.First(&newUser)
println(newUser.Name)
println(newUser.Car.Type)
println(newUser.Account.Powerlevel)
// Explicitly preload
db.Preload("Car").First(&newUser)
db.Preload("Account").First(&newUser)
println(newUser.Name)
println(newUser.Car.Type)
println(newUser.Account.Powerlevel)
}
The output of the two prints are :
Jim Bob
0
0
Jim Bob
1994
9001
Why does getting the model over db.First(...) not automatically preload when i can preload them manually perfectly fine ?
Firstly I would recommend reading the docs.
A bit of explanation here. It appears that you are using an old version more than likely. The updated docs explain to use this tag
gorm:"PRELOAD"
, which by default is set to true. So if you would like to disable a field usegorm:"PRELOAD:false"
.Afterward, use must use
db.Set("gorm:auto_preload", true)
for it to fetch properly. If you are going to use the preload fetch through the application then you can reassign db as such to have the auto_preload feature:Example:
Output: