Your Question
I'd like to select something when using Smart Select Fields for example, Location table is
type Location struct {
gorm.Model
Name string `gorm:"not null"`
X int32 `gorm:"not null; index"`
Y int32 `gorm:"not null; index"`
Address string `gorm:"not null"`
}
And I'd like to select more columns such as Distance in example
type APILocation struct {
Id uint
Name string
X int32
Y int32
Address string
Distance int32 // Location table doesn't have this field
}
In this case,
db.
Select(fmt.Sprintf("(x - %v) * (x - %v) + (y - %v) * (y - %v) as Distance", X, X, Y, Y)).
Model(&model.Location{}).
Find(&model.APILocation{})
It select every fields in APILocation plus distance. But if I use parameterized queries, like
db.
Select("(x - ?) * (x - ?) + (y - ?) * (y - ?) as Distance", home.X, home.X, home.Y, home.Y).
Model(&model.Location{}).
Find(&model.APILocation{})
Select overwrites Smart Select Fields and it selects only distance
How can I select additional custom fields with smart select fields?
The document you expected this should be explained
It explains only how to use smart select fields.
Expected answer
How to select additional fields
Comment From: a631807682
db.
- Select("(x - ?) * (x - ?) + (y - ?) * (y - ?) as Distance", home.X, home.X, home.Y, home.Y).
+ Select("*,(x - ?) * (x - ?) + (y - ?) * (y - ?) as Distance", home.X, home.X, home.Y, home.Y).
Model(&model.Location{}).
Find(&model.APILocation{})
I didn't quite understand your question, if you want to include other fields
Comment From: SuhwanCha
@a631807682 Sorry for the confusing question. If I use the smart select field, only fields in the struct will be selected automatically. My question is how to select additional fields with smart select fields, which means not to select every field but smart select fields plus something, not using asterisk
Comment From: a631807682
You can use scope, first you need to parse the schema, and then automatically add schema.DBNames to the original select.
https://gorm.io/docs/scopes.html#content-inner
tx.Statement.Schema.Parse
...
for sch range tx.Statement.Schema.DBNames {
...
}
...
tx.Statement.Selects = ...