搜索
首页后端开发Golang使用Go通过Gorm通过外键对数据进行排序

使用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中文网其他相关文章!

声明
本文转载于:stackoverflow。如有侵权,请联系admin@php.cn删除
GO的选择语句:多路复用并发操作GO的选择语句:多路复用并发操作Apr 24, 2025 pm 05:21 PM

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,执行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

GO中的高级并发技术:上下文和候补组GO中的高级并发技术:上下文和候补组Apr 24, 2025 pm 05:09 PM

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,确保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,确保Allimizegoroutines,确保AllizeNizeGoROutines,确保AllimizeGoroutines

使用微服务体系结构的好处使用微服务体系结构的好处Apr 24, 2025 pm 04:29 PM

goisbeneformervicesduetoitssimplicity,效率,androbustConcurrencySupport.1)go'sdesignemphasemphasizessimplicity and效率,Idealformicroservices.2))其ConcconcurnCurnInesSandChannelsOdinesSallessallessallessAlloSalosalOsalOsalOsalOndlingConconcConccompi.3)

Golang vs. Python:利弊Golang vs. Python:利弊Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang和C:并发与原始速度Golang和C:并发与原始速度Apr 21, 2025 am 12:16 AM

Golang在并发性上优于C ,而C 在原始速度上优于Golang。1)Golang通过goroutine和channel实现高效并发,适合处理大量并发任务。2)C 通过编译器优化和标准库,提供接近硬件的高性能,适合需要极致优化的应用。

为什么要使用Golang?解释的好处和优势为什么要使用Golang?解释的好处和优势Apr 21, 2025 am 12:15 AM

选择Golang的原因包括:1)高并发性能,2)静态类型系统,3)垃圾回收机制,4)丰富的标准库和生态系统,这些特性使其成为开发高效、可靠软件的理想选择。

Golang vs.C:性能和速度比较Golang vs.C:性能和速度比较Apr 21, 2025 am 12:13 AM

Golang适合快速开发和并发场景,C 适用于需要极致性能和低级控制的场景。1)Golang通过垃圾回收和并发机制提升性能,适合高并发Web服务开发。2)C 通过手动内存管理和编译器优化达到极致性能,适用于嵌入式系统开发。

golang比C快吗?探索极限golang比C快吗?探索极限Apr 20, 2025 am 12:19 AM

Golang在编译时间和并发处理上表现更好,而C 在运行速度和内存管理上更具优势。1.Golang编译速度快,适合快速开发。2.C 运行速度快,适合性能关键应用。3.Golang并发处理简单高效,适用于并发编程。4.C 手动内存管理提供更高性能,但增加开发复杂度。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。