I have the following structs:
type User struct {
gorm.Model
Username string
Orders []Order
}
type Order struct {
gorm.Model
UserID uint
Price float64
}
And try to load the rows from the database with a helper function:
// Return collection of resources
func LoadRows(dest interface{}) error {
db.Preload("Orders").Find(&dest)
// [...]
return fiber.jSON([...])
}
Now I want to load all Users with the orders preloaded:
func main() {
response := LoadRows([]User);
}
All I get are the users without the preloaded orders. There is also no query in the console that loads the orders. When I change the LoadRows function to the following, everything is working as expected. But then I can not load data in a flexible way:
// Return collection of resources
func LoadRows(dest interface{}) error {
var result []User // This is needed, otherwise orders are not loaded
db.Preload("Orders").Find(&result)
// Now data includes users and orders.
// [...]
return fiber.jSON([...])
}
The document you expected this should be explained
https://gorm.io/docs/preload.html
Expected answer
Is it possible to load data with relations in a flexible way or do I always have to set the exact type I want to load?
Comment From: a631807682
Is it possible to load data with relations in a flexible way or do I always have to set the exact type I want to load?
You have to set the exact type, either via generics or via reflect.