我不知道,一直呆在这里...... 所以我需要根据外键对数据进行排序。
我一直在尝试一些代码(见下文),但根本不起作用。
这是我的结构数据:
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)
我使用连接方法,我可以根据从角色模型连接的字段来订购数据