GORM Playground Link
https://github.com/go-gorm/playground/pull/427
Description
The following Join statement not working as expected -->
Joins("JOIN unnest(ARRAY[?]::int[]) WITH ORDINALITY AS x(id, order_nr) ON x.id = users.id", []uint{2, 1, 3})
The slice of IDs receives an extra parenthesis, which makes the query fail.
SELECT "users"."id","users"."created_at","users"."updated_at","users"."deleted_at","users"."name","users"."age","users"."birthday","users"."company_id","users"."manager_id","users"."active" FROM "users" JOIN unnest(ARRAY[(2,1,3)]::int[]) WITH ORDINALITY AS x(id, order_nr) ON x.id = users.id WHERE "users"."deleted_at" IS NULL ORDER BY x.order_nr
Comment From: jinzhu
Use clause.Expr like clause.Expr{SQL: "FIELD(id,?)", Vars: []interface{}{[]int{1, 2, 3}}, WithoutParentheses: true}
refer https://gorm.io/docs/query.html#Order
Comment From: joelazar
@jinzhu thank you very much. Got it working with:
Clauses(
clause.From{
Joins: []clause.Join{
{
Expression: clause.Expr{SQL: "JOIN unnest(ARRAY[?]::int[]) WITH ORDINALITY AS x(id, order_nr) ON x.id = users.id", Vars: []interface{}{[]uint{2,1,3}, WithoutParentheses: true},
},
},
},
).
Order("x.order_nr")