-
I would like to add order by clause programmatically. What I have so far is by creating a slice of qm.QueryMod and then looping through a user defined map to sort. The sortBy := map[string]string{
"description": "asc",
"created_at": "desc",
}
var mods []qm.QueryMod
mods = append(mods, qm.Where("description LIKE ?", "%"+description+"%"))
mods = append(mods, qm.Limit(limit))
mods = append(mods, qm.Offset(offset))
for col, order := range sortBy {
mods = append(mods, qm.OrderBy(fmt.Sprintf("%s %s", col, order)))
}
query := models.Books(mods...)
res, err := query.All(ctx, r.db)
if err != nil {
return nil, err
} I get the intended sql query SELECT *
FROM `books`
WHERE (description LIKE '%t%')
AND (`books`.`deleted_at` is null)
ORDER BY description asc, created_at desc
LIMIT 1 OFFSET 1; Is there a better way to construct the query using query mod? Or is there a helper that can add res, err := models.Books(
qm.Where("description LIKE ?", "%"+description+"%"),
qm.Limit(limit),
qm.Offset(offset),
).
All(ctx, r.db) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
There's nothing better than this. Though it doesn't seem like this is too onerous to make a little function in your code that does mods := []qm.QueryMod{
qm.Where("description LIKE ?", "%"+description+"%"),
qm.Limit(limit),
qm.Offset(offset),
}
mods = OrderByFromMap(map) |
Beta Was this translation helpful? Give feedback.
There's nothing better than this. Though it doesn't seem like this is too onerous to make a little function in your code that does
OrderByFromMap
since all the types are generic. You can re-assign to mods and the function can change it if it's necessary or return the input if not.