Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

go - Select the latest N items sorted in oldest to newer

I am trying to select the latest messages by date of creation with the following entity.

type Message struct {
    ID        uuid.UUID `gorm:"primaryKey;type:uuid;not null" json:"id"`
    CreatedAt time.Time `json:"createdAt"`
    Content   string    `json:"content"`
    Room      *Room     `json:"room,omitempty"`
    RoomID    uuid.UUID `gorm:"type:uuid;not null" json:"-"`
    User      *User     `json:"author,omitempty"`
    UserID    uuid.UUID `gorm:"type:uuid;not null" json:"-"`
}

I've come up with the following query:

var messages []entity.Message

// get latest 10 items 
// newest by date will be at the top
if err := r.db.
    Where(&entity.Message{RoomID: room.ID}).
    Order("created_at DESC").
    Limit(10).
    Preload("User").
    Find(&messages).Error; err != nil {
    return nil, err
}

We retrieve the latest 10 messages in descending order by creation date. The problem is that I need to reverse the order after that.

How can we reorder the result ascendingly? (last message should be at the end)

question from:https://stackoverflow.com/questions/66063886/select-the-latest-n-items-sorted-in-oldest-to-newer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using a subquery is nice, but what about simply reversing the slice after you retrieve it? ??

for i, j := 0, len(messages)-1; i < j; i++, j--) {
    messages[i], messages[j] = messages[j], messages[i]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...