Sql 使用关联字段对记录进行排序
我想订购GORM V2中具有关联记录的记录 我有两个结构:Sql 使用关联字段对记录进行排序,sql,sorting,go-gorm,Sql,Sorting,Go Gorm,我想订购GORM V2中具有关联记录的记录 我有两个结构: type Client struct { gorm.Model UUID uuid.UUID `gorm:"type:uuid"` ClientProfile ClientProfile } type ClientProfile struct { gorm.Model ClientID uint F
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
struct中的字段对这些记录进行排序
我试过但没有成功:
db.
Preload(clause.Associations).
Order("client_profiles.last_name DESC").
Find(&clients)
这会引发以下错误:
错误:表“客户端配置文件”(SQLSTATE 42P01)的子句条目中缺少
Find with Preload首先查询
客户机
表,然后使用第一个查询的ID查询客户机配置文件
表,因此它无法根据第二个查询的数据对第一个查询进行排序
由于这是一个HasOne关系,您可以使用它,它实际上对两个实体都使用一个查询。然后,您将能够按照相关实体的字段进行排序:
err:=db。
模型(&客户端{})。
联接(“ClientProfile”)。
订单(“客户档案。姓氏描述”)。
查找(&客户端)。
错误
//处理错误