diff --git a/internal/dbtest/query_test.go b/internal/dbtest/query_test.go index 81f9abe99..5266d2211 100644 --- a/internal/dbtest/query_test.go +++ b/internal/dbtest/query_test.go @@ -1008,6 +1008,22 @@ func TestQuery(t *testing.T) { Join("JOIN user ON user.id = story.user_id"). Where("user.id = ?", 1) }, + func(db *bun.DB) schema.QueryAppender { + return db.NewSelect().Model(new(Story)). + Column("id", "name"). + ColumnExpr("@TableAlias.name AS user_name"). + Join("LEFT JOIN user AS u"). + JoinOn("u.id = @TableAlias.user_id"). + Order("id") // If I need to sort according to the ID of the main table (student) + }, + func(db *bun.DB) schema.QueryAppender { + return db.NewSelect().Model(new(Story)). + Column("id", "name"). + ColumnExpr("@TableAlias.name AS user_name"). + Join("LEFT JOIN user AS u"). + JoinOn("u.id = @TableAlias.user_id"). + Order("u.id") // If I need to sort by the ID of the associated table (user) + }, } timeRE := regexp.MustCompile(`'2\d{3}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(\.\d+)?(\+\d{2}:\d{2})?'`) diff --git a/query_select.go b/query_select.go index c0e145110..76ef8d44f 100644 --- a/query_select.go +++ b/query_select.go @@ -781,11 +781,22 @@ func (q *SelectQuery) appendOrder(fmter schema.Formatter, b []byte) (_ []byte, e if len(q.order) > 0 { b = append(b, " ORDER BY "...) - for i, f := range q.order { + for i, ord := range q.order { if i > 0 { b = append(b, ", "...) } - b, err = f.AppendQuery(fmter, b) + + // Auto add alias for order column added via Column() method if the column in the table FieldMap + if ord.Args == nil && q.table != nil { + if field, ok := q.table.FieldMap[ord.Query]; ok { + b = append(b, q.table.SQLAlias...) + b = append(b, '.') + b = append(b, field.SQLName...) + continue + } + } + + b, err = ord.AppendQuery(fmter, b) if err != nil { return nil, err }