乐闻世界logo
搜索文章和话题

How do I stop GORM from sorting my preload by ID?

1个答案

1

In GORM database operations, we frequently encounter common requirements or issues, such as controlling the loading order of data during eager loading. By default, GORM sorts the related data of preloaded associations by the primary key (ID). If you wish to customize the sorting order or disable this default behavior, you can achieve it through several methods:

1. Using Subqueries for Preloading

We can specify the order of preloaded data by writing a subquery. For example, if you have a User model and an Order model, and each user has multiple orders, you might prefer sorting by the CreatedAt timestamp rather than the ID. Example code:

go
db.Preload("Orders", func(db *gorm.DB) *gorm.DB { return db.Order("created_at DESC") }).Find(&users)

Here, we leverage the second parameter of the Preload method, passing a function that returns a *gorm.DB type. This function uses the Order method to define the sorting rule.

2. Global Scope

If you want to apply a sorting method to every query, you can define a global scope. For example:

go
func OrderScope(order string) func(db *gorm.DB) *gorm.DB { return func(db *gorm.DB) *gorm.DB { return db.Order(order) } } db.Scopes(OrderScope("created_at DESC")).Preload("Orders").Find(&users)

This approach enables reusing and managing sorting logic uniformly, enhancing code maintainability.

3. Using Joins Function

For more complex custom handling (e.g., sorting based on fields in the associated table), you can use the Joins function:

go
db.Joins("JOIN orders ON orders.user_id = users.id"). Order("orders.created_at DESC"). Preload("Orders"). Find(&users)

This ensures GORM sorts the main query by orders.created_at while also preloading Orders.

Summary

Through these methods, you can flexibly control GORM's preloading sorting. It is recommended to choose the appropriate method based on actual business needs, considering query performance and code maintainability. In practice, prioritize performance while ensuring code clarity and manageability.

2024年7月31日 00:20 回复

你的答案