【问题标题】:Sort records with an associated field使用关联字段对记录进行排序
【发布时间】:2021-07-06 17:31:39
【问题描述】:

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

这会引发以下错误:

错误:缺少表“client_profiles”的 FROM 子句条目 (SQLSTATE 42P01)

【问题讨论】:

    标签: sql sorting go-gorm


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      • 2020-04-16
      • 1970-01-01
      • 2011-04-21
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多