Your Question
I'm attempting to add a named arg for an ORDER BY, but cannot get it to work.
I'm using a Postgres database if the error looks syntax specific.
I have the following (pruned to make more readable):
args := map[string]interface{}{
"sort": "created_at",
}
var list []Object
result := db.Raw(`
SELECT *
FROM object
ORDER BY @sort`,
args,
).Debug().Find(&list)
But this resolves to:
SELECT *
FROM object
ORDER BY 'created_at'
When executed, it doesn't seem to consider the ORDER BY, I think due to the '' around created_at.
Is there any way to add a custom parameter ORDER BY for raw SQL? I believe chaining an .Order(...) function won't work with the Raw function (I wasn't able to get it to work).
The document you expected this should be explained
https://gorm.io/docs/sql_builder.html#Named-Argument
Expected answer
Any way can I add a parameterised ORDER BY for a raw SQL query!
Comment From: anhnmt
I had the same situation, i used ToSQL to see where the problem was and found the error in this line ORDER BY 'msg''DESC'
https://gorm.io/docs/sql_builder.html#ToSQL