diff --git a/cabana/list_schema.go b/cabana/list_schema.go index 19d0c7d..7dee55a 100644 --- a/cabana/list_schema.go +++ b/cabana/list_schema.go @@ -227,7 +227,7 @@ func compileColumns(pluginID string, ctl pact.AdminController, fsys fs.FS, colPa return nil, bootErr(pluginID, ctl.ID(), colPath, fmt.Errorf("column %s is not on the model", key)) } } - sortable := true + sortable := spec.Relation == "" if spec.Sortable != nil { sortable = *spec.Sortable } diff --git a/cabana/query.go b/cabana/query.go index 1852e02..a10bff6 100644 --- a/cabana/query.go +++ b/cabana/query.go @@ -123,7 +123,7 @@ func ExecuteList(ctx context.Context, db *gorm.DB, cc *CompiledController, in Li if err := q.Session(&gorm.Session{}).Count(&total).Error; err != nil { return nil, err } - q = applyListOrder(q, model, sortCol, sortDesc) + q = applyListOrder(q, cc.List, model, sortCol, sortDesc) for _, col := range cc.List.Columns { if col.Relation != "" { q = q.Preload(col.Relation) @@ -207,7 +207,7 @@ func normalizeSort(schema *ListSchema, in ListInput) (string, bool, error) { break } } - if match == nil || !match.Sortable || match.Relation != "" { + if match == nil || !match.Sortable { return "", false, listInvalid("sort", "is not a sortable column") } dir := in.Dir @@ -220,12 +220,23 @@ func normalizeSort(schema *ListSchema, in ListInput) (string, bool, error) { return match.Key, dir == "desc", nil } -func applyListOrder(db *gorm.DB, model any, column string, desc bool) *gorm.DB { +func applyListOrder(db *gorm.DB, schema *ListSchema, model any, column string, desc bool) *gorm.DB { table := tableName(model) pk := primaryColumn(model) if column != "" { + orderTable := table + orderColumn := column + for _, col := range schema.Columns { + if col.Key != column || col.Relation == "" { + continue + } + orderTable = col.Relation + orderColumn = col.Select + db = db.Joins(col.Relation) + break + } db = db.Order(clause.OrderByColumn{ - Column: clause.Column{Table: table, Name: column}, + Column: clause.Column{Table: orderTable, Name: orderColumn}, Desc: desc, }) }