Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

order by with specific column values #4036

Open
forwardever opened this issue Apr 26, 2024 · 1 comment
Open

order by with specific column values #4036

forwardever opened this issue Apr 26, 2024 · 1 comment

Comments

@forwardever
Copy link

Hello,

what is the best way to sort results by column values.

MySQL example:
SELECT * FROM table ORDER BY FIELD(ID,1,5,4,3)

@forwardever forwardever changed the title order by with specific value order by with specific column values Apr 26, 2024
@henrywoody
Copy link
Contributor

I don't think there is a built-in function for this (could be wrong though), but you can use custom ordering like this:

query := client.MyModel.Query()
query.Order(func (s *sql.Selector) {
	s.OrderExpr(sql.ExprFunc(func(b *sql.Builder) {
		b.WriteString("FIELD(")
		b.Ident(mymodel.FieldID)
		b.WriteString(", 1, 5, 4, 3)")
	}))
})

or if those values come from user input:

query := client.MyModel.Query()
query.Order(func (s *sql.Selector) {
	s.OrderExpr(sql.ExprFunc(func(b *sql.Builder) {
		b.WriteString("FIELD(")
		b.Ident(mymodel.FieldID)
		for _, value := range values {
			b.WriteString(", ")
			b.Arg(value)
		}
		b.WriteString(")")
	}))
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants