对具有关联字段的记录进行排序

Sort records with an associated field

我想在 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)

这会引发以下错误:

ERROR: missing FROM-clause entry for table "client_profiles" (SQLSTATE 42P01)

Find with Preload先查询clients table,然后用第一个ID查询client_profiles table,所以无法排序第一个查询来自第二个数据。

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

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