📅  最后修改于: 2023-12-03 14:41:37.041000             🧑  作者: Mango
GORM is a popular ORM (Object-Relational Mapping) library for Go programming language. It provides a simple and easy-to-use interface to interact with various databases.
One of the essential functionalities of a database is sorting the query result based on specific criteria. And GORM also provides a flexible way to sort the data using the Order
method.
Order
The Order
method is an extension method of gorm.DB
type, which takes the sorting criteria as its parameter. Here's the syntax of Order
method:
func (db *gorm.DB) Order(value interface{}, reorder ...bool) *gorm.DB
value
(interface{}): The sorting criteria in the form of a string literal or a struct field.reorder
(bool): Optional. If set to true
, the previous Order
clauses will be cleared before adding the new one.To sort the query result in ascending order, we need to provide the sorting criteria to the Order
method. Here's an example:
db.Order("name asc").Find(&users)
In the above example, we are sorting the users
table by their name
field in ascending order.
To sort the query result in descending order, we need to add the desc
keyword after the sorting field. Here's an example:
db.Order("age desc").Find(&users)
In the above example, we are sorting the users
table by their age
field in descending order.
We can also sort the query result by the field of the model struct. Here's an example:
type User struct {
ID uint
Name string
Age uint
}
db.Order("age desc").Order("name asc").Find(&users)
In the above example, we are sorting the users
table by their age
field in descending order and then by their name
field in ascending order.
GORM provides an optional reorder
parameter to clear previous order clauses before adding the new one. Here's an example:
db.Order("name asc").Order("age desc", true).Find(&users)
In the above example, we are clearing the previous Order
clause before adding a new one to sort the users
table first by their name
field in ascending order and then by their age
field in descending order.
In this article, we learned how to use the Order
method of GORM to sort the query result based on specific criteria. GORM provides an easy-to-use interface to interact with various databases and perform CRUD (Create, Read, Update, and Delete) operations.