
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")
}
两者都不起作用,你们以前经历过这种情况吗?
使用模板与程序分离的方式构建,依靠专门设计的数据库操作类实现数据库存取,具有专有错误处理模块,通过 Email 实时报告数据库错误,除具有满足购物需要的全部功能外,成新商城购物系统还对购物系统体系做了丰富的扩展,全新设计的搜索功能,自定义成新商城购物系统代码功能代码已经全面优化,杜绝SQL注入漏洞前台测试用户名:admin密码:admin888后台管理员名:admin密码:admin888
真的需要您的建议...谢谢
解决方法
所以,在浏览了这么多参考资料之后,我明白了这一点。这就是我的答案,以防将来每个人都面临同样的问题:
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)
我使用连接方法,我可以根据从角色模型连接的字段来订购数据









