3

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

}
Casper
  • 173
  • 2
  • 11
  • 1
    You have this part of code where you use `Id DESC` sort: `queryBuider.Model(&models.News{}).Where(q).Order("Id DESC")`. The other `Order` function call is probably overwritten with this one. Try removing the `Id DESC` sort and check if it will help you. – Emin Laletovic Jul 18 '22 at 17:06

1 Answers1

4

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)
colm.anseo
  • 19,337
  • 4
  • 43
  • 52