Search code examples
gogo-gormgo-gin

Can't sort in GORM


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,
    })

}

Solution

  • 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)