You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Looking for a way to order by a struct field name rather than the DB column name.
Something like this:
typeSomeParamsstruct {
SortFieldstring`json:"sortField"`SortDescbool`json:"sortDesc"`
}
typeSomeViewstruct {
SomeValuestring`json:"someValue" pagination:"sortable"`// ... some other fields, some sortable, some not
}
typeSomeModelstruct {
gorm.ModelSomeValuestring// other fields...// Field names and types match from SomeModel to SomeView
}
ffuncsudoCodeExample(db*gorm.DB) {
// comes from apiparams:=SomeParams{
SortField: "someValue",
SortDesc: true,
}
// getSortable uses reflection to return field.Name and JSON Name specified in Tagsortable:=getSortable(SomeView{}) // -> [{Name: "SomeValue", JSONName: "someValue"}, ...]// findSortableName iterates over sortable slice and returns field namefieldName, ok:=findSortableName(sortable, "someValue") // -> "SomeValue", truevarrecords []SomeModel// Note: clause.OrderByField doesn't currently exist (concept)db.Order(clause.OrderByField{
Name: fieldName,
Desc: params.SortDesc,
}).Find(&records)
// or perhaps when joins are used:db.Order(clause.OrderByField{
Model: SomeModel{},
Name: fieldName,
Desc: params.SortDesc,
}).Find(&records)
}
Is something like this possible?
My goal is to map the JSON view name to the database column name. The view field name generally matches the model field name. I have an existing function that gets the struct field name from a JSON name.
The use-case is I want to specify which fields in the view are sortable. I have search endpoints that allow users to sort the results. I do not want to expose the table column names and have the view names used instead.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Looking for a way to order by a struct field name rather than the DB column name.
Something like this:
Is something like this possible?
My goal is to map the JSON view name to the database column name. The view field name generally matches the model field name. I have an existing function that gets the struct field name from a JSON name.
The use-case is I want to specify which fields in the view are sortable. I have search endpoints that allow users to sort the results. I do not want to expose the table column names and have the view names used instead.
Beta Was this translation helpful? Give feedback.
All reactions