I wonder if it is possible to preload only selected fields of nested database objects with gorm. Right now, I am trying to do it like this:
db.Preload("Children",` func(db *gorm.DB) *gorm.DB {
return DB.Select("id")
}).First(&labelset, id)
The result is then:
{
"ID": 1,
"CreatedAt": "2018-06-29T11:32:21.293892+02:00",
"UpdatedAt": "2018-06-29T11:32:21.293892+02:00",
"DeletedAt": null,
"description": "Root test",
"parent_id": 0,
"children": []
}
If I replace the "id" with "*", I get:
{
"ID": 1,
"CreatedAt": "2018-06-29T11:32:21.293892+02:00",
"UpdatedAt": "2018-06-29T11:32:21.293892+02:00",
"DeletedAt": null,
"description": "Root test",
"parent_id": 0,
"children": [
{
"ID": 2,
"CreatedAt": "2018-06-29T11:32:38.639568+02:00",
"UpdatedAt": "2018-06-29T11:32:38.639568+02:00",
"DeletedAt": null,
"description": "Child test",
"parent_id": 1,
"children": null
}
]
}
Actually, I would like to have something in between, where I can select the fields in the children array (e.g. the id only).
Any idea, if this is possible, or what am I doing wrong?
go version)?Running go1.9.2 darwin/amd64
SQLITE
Must select foreignkey: return db.Select("id, parent_id")
That comes much closer to what I wanted. I can omit most of the other attributes when converting to json, while they are null. Still have the 'parent_id' then populated, but that's better than having also everything else.
Thank you.
But apparently, you can't just return the IDs (of the children), can you?
have same problem
@phev8 Is there a better way to scan the specified fields? They are null, it looks too bloated
@phev8 In my case, a column name from Preload table was wrong and as @yuys said, must to select the foreignkey... to debug it (to know how your query is going) just set db.LogMode(true) before query command or at begging of opened connection (if you wanna to track everything)
This issue will be automatically closed because it is marked as GORM V1 issue, we have released the public testing GORM V2 release and its documents https://v2.gorm.io/docs/ already, the testing release has been used in some production services for a while, and going to release the final version in following weeks, we are still actively collecting feedback before it, please open a new issue for any suggestion or problem, thank you
Also check out https://github.com/go-gorm/gorm/wiki/GORM-V2-Release-Note-Draft for how to use the public testing version and its changelog
Most helpful comment
Must select foreignkey: return db.Select("id, parent_id")