无法在GORM中进行排序。

huangapple go评论94阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2022年7月19日 00:05:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/73025363.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定