GORM Playground Link
- https://github.com/go-gorm/playground/pull/626
Description
Consider these models:
type Skill struct {
gorm.Model
ManagerID uint
Name string
}
type Manager struct {
gorm.Model
Name string
Skills []Skill
}
type Project struct {
gorm.Model
Name string
ManagerID uint
Manager Manager
}
A Project has one Manager who can have many Skill.
One could use the following code to retrieve a Project along with its associated Manager and Skills:
var result Project
DB.Joins("Manager").Preload("Manager.Skills").First(&result, myProjectID)
I was excepting such code to generate at most two queries:
- SELECT * FROM projects with a LEFT JOIN managers clause
- SELECT * FROM skills
But it turns out that it generates an additional, unnecessary query:
- SELECT * FROM managers
The has-many association Skills should have been loaded by using the primary keys returned in the first query with the LEFT JOIN managers clause.
There's no point in having an additional separate query in this case.
Thanks for your help!