日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

php小編西瓜今天給大家分享一個使用Go語言和Gorm庫來通過外鍵對數據進行排序的方法。在大多數數據庫中,我們經常需要根據外鍵關聯的字段對數據進行排序。通過使用Gorm庫,我們可以輕松地實現這一功能。本文將教你如何使用Gorm的Preload方法和Order方法來實現外鍵排序,讓你的數據查詢更加靈活和高效。讓我們一起來看看具體的操作步驟吧!

問題內容

我不知道,一直呆在這里……
所以我需要根據外鍵對數據進行排序。

我一直在嘗試一些代碼(見下文),但根本不起作用。

這是我的結構數據:

type User struct {
    ID          string          `gorm:"primarykey" json:"id"`
    Name        string          `gorm:"not null" json:"name"`
    Email       string          `gorm:"unique" json:"email"`
    Password    string          `gorm:"not null" json:"password"`
    Phone       string          `json:"phone"`
    AccountType string          `json:"account_type"`
    Key         string          `json:"key"`
    RoleID      string          `gorm:"not null" json:"role_id"`
    Role        role.Role       `gorm:"foreignKey:RoleID" json:"role"`
    CreatedAt   time.Time       `json:"-"`
    UpdatedAt   time.Time       `json:"-"`
    DeletedAt   gorm.DeletedAt  `gorm:"index" json:"-"`

}

type Role struct {
  ID          string                  `gorm:"primarykey" json:"id"`
  Name        string                  `gorm:"not null" json:"name"`
  TierLevel   uint                    `gorm:"not null" json:"tier_level"`
  CreatedAt   time.Time               `gorm:"not null;default:current_timestamp" json:"-"`
  UpdatedAt   time.Time               `gorm:"not null;default:current_timestamp" json:"-"`
  DeletedAt   gorm.DeletedAt          `gorm:"index" json:"-"`
}

登錄后復制

我想根據角色對數據進行排序,所以我寫了這樣的代碼

# my first trying #
result = query.Preload("Role", func(db *gorm.DB) *gorm.DB {
                return db.Order(orderString)
            }).Limit(limit).Offset(offset).Find(&users)

# my second trying #
result = query.Preload("Role").Limit(limit).Offset(offset).Find(&users)
            roles := []roleModel.Role{} --> this roleModel had been importing in this file 
            for i := range roles {
                result.Model(&roles[i]).Order("roles.name ASC")
            }

登錄后復制

兩者都不起作用,你們以前經歷過這種情況嗎?

真的需要您的建議…謝謝

解決方法

所以,在瀏覽了這么多參考資料之后,我明白了這一點。這就是我的答案,以防將來每個人都面臨同樣的問題:

parts := strings.Split(sortBy, ".") --> this sortBy was kind of like "role.name"
field := strings.TrimSpace(parts[1])
orderString = fmt.Sprintf("roles.%s %s", field, sortOrder)
result = query.Limit(limit).Offset(offset).Joins("JOIN roles ON users.role_id = roles.id").Order(orderString).Find(&users)

登錄后復制

我使用連接方法,我可以根據從角色模型連接的字段來訂購數據

分享到:
標簽:Go語言
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定