go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
36.71k stars 3.92k forks source link

[Raw SQL] Named Args ORDER BY #6701

Open mingles opened 10 months ago

mingles commented 10 months ago

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!

anhnmt commented 7 months ago

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