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)
登錄后復制
我使用連接方法,我可以根據從角色模型連接的字段來訂購數據