Search code examples
sortinggogo-gorm

Sorting Data With Foreign Key With Gorm using Go


I have no idea and stuck being here... So I need to sorting my data based on foreign key.

I've been trying a few code (see that below) but didn't work at all.

This is my structure data:

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:"-"`
}

I want to sort data based on role, so I wrote the code like this

# 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")
            }


both not work, do you guys have ever experienced this before?

Really need your advices... thank you


Solution

  • So, after browsing so much references, I got this covered. So this is my answer, in case everyone in the future faces the same issue:

    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)
    

    I use method Joins and I could ordering data base on field joined from role model