使用关联字段对记录进行排序



我想在GORM V2中订购带有关联记录的记录。

我有两个结构:

type Client struct {
gorm.Model
UUID                   uuid.UUID `gorm:"type:uuid"`
ClientProfile          ClientProfile
}
type ClientProfile struct {
gorm.Model
ClientID         uint
FirstName        string
LastName         string
}

现在,我可以用加载所有记录

db.
Preload(clause.Associations).
Find(&clients).

现在如何使用ClientProfile结构中的字段对这些记录进行排序?

我尝试了但没有成功:

db.
Preload(clause.Associations).
Order("client_profiles.last_name DESC").
Find(&clients)

这会引发以下错误:

错误:缺少表"的FROM子句条目;client_profiles";(SQLSTATE 42P01(

Find with Preload先查询clients表,然后用第一个表中的ID查询client_profiles表,因此无法按第二个表的数据对第一个查询进行排序。

由于这是一个HasOne关系,您可以使用Joins Preloading,它实际上对两个实体都使用了一个查询。然后,您将能够按照相关实体的字段进行排序:

err := db.
Model(&Client{}).
Joins("ClientProfile").
Order("client_profiles.last_name DESC").
Find(&clients).
Error
// handle error

最新更新