使用Go透過Gorm透過外鍵對資料進行排序
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透過Gorm透過外鍵對資料進行排序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Go語言中用於浮點數運算的庫介紹在Go語言(也稱為Golang)中,進行浮點數的加減乘除運算時,如何確保精度是�...

GoLand中自定義結構體標籤不顯示怎麼辦?在使用GoLand進行Go語言開發時,很多開發者會遇到自定義結構體標籤在�...

Go爬蟲Colly中的Queue線程問題探討在使用Go語言的Colly爬蟲庫時,開發者常常會遇到關於線程和請求隊列的問題。 �...

Go語言中使用RedisStream實現消息隊列時類型轉換問題在使用Go語言與Redis...

Go語言中字符串打印的區別:使用Println與string()函數的效果差異在Go...

Go語言中結構體定義的兩種方式:var與type關鍵字的差異Go語言在定義結構體時,經常會看到兩種不同的寫法:一�...

Go編程中的資源管理:Mysql和Redis的連接與釋放在學習Go編程過程中,如何正確管理資源,特別是與數據庫和緩存�...

Go語言中哪些庫是大公司開發或知名開源項目?在使用Go語言進行編程時,開發者常常會遇到一些常見的需求,�...
