英文:
Can't sort in GORM
问题
我有一个News
结构体,我想按照日期降序
的方式显示它们。但是它以常规方式按照id显示给我。
结构体:
type News struct {
Id int `json:"id" gorm:"primary_key, AUTO_INCREMENT"`
...
CreatedAt time.Time `json:"created_at"`
}
函数:
func GetAllNews(q *models.News, pagination *models.Pagination) (*[]models.News, error) {
var news []models.News
offset := (pagination.Page - 1) * pagination.Limit
queryBuider := config.DB.Limit(pagination.Limit).Offset(offset).Order(pagination.Sort)
result := queryBuider.Model(&models.News{}).Where(q).Order("CreatedAt DESC").Find(&news)
if result.Error != nil {
msg := result.Error
return nil, msg
}
return &news, nil
}
func GetAllNews_by_page(c *gin.Context) {
pagination := GeneratePaginationFromRequest(c)
var news models.News
prodLists, err := GetAllNews(&news, &pagination)
if err != nil {
c.JSON(http.StatusBadRequest, err.Error())
return
}
c.JSON(http.StatusOK, gin.H{
"data": prodLists,
})
}
英文:
I have a News
structure, I want to display them in descending date order
. But he displays them to me by id in the usual way
Struct:
type News struct {
Id int `json:"id" gorm:"primary_key, AUTO_INCREMENT"`
...
CreatedAt time.Time `json:"created_at"`
}
Funcs:
func GetAllNews(q *models.News, pagination *models.Pagination) (*[]models.News, error) {
var news []models.News
offset := (pagination.Page - 1) * pagination.Limit
queryBuider := config.DB.Limit(pagination.Limit).Offset(offset).Order(pagination.Sort)
result := queryBuider.Model(&models.News{}).Where(q).Order("Id DESC").Find(&news)
if result.Error != nil {
msg := result.Error
return nil, msg
}
return &news, nil
}
func GetAllNews_by_page(c *gin.Context) {
pagination := GeneratePaginationFromRequest(c)
var news models.News
prodLists, err := GetAllNews(&news, &pagination)
if err != nil {
c.JSON(http.StatusBadRequest, err.Error())
return
}
c.JSON(http.StatusOK, gin.H{
"data": prodLists,
})
}
答案1
得分: 4
从GORM
文档中,例如:
db.Order("age desc, name").Find(&users)
// SELECT * FROM users ORDER BY age desc, name;
所以首先根据created_at
列对结果进行排序 - 如果有两条记录具有相同的时间戳,可以将id
列列为第二个(以确保重复查询返回一致的结果):
result := queryBuider.Model(&models.News{}).Where(q).Order("created_at DESC, id DESC").Find(&news)
英文:
From the GORM
docs e.g.
db.Order("age desc, name").Find(&users)
// SELECT * FROM users ORDER BY age desc, name;
so order your results based on the created_at
column first - and you can list id
second in case there's two records with the same timestamp (to ensure repeated queries return consistent results):
result := queryBuider.Model(&models.News{}).Where(q).Order("created_at DESC, id DESC").Find(&news)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论