【问题标题】:How to query a one to many relationship with go-pg如何使用 go-pg 查询一对多关系
【发布时间】:2024-01-23 14:11:01
【问题描述】:

我想查询一对多关系。我有以下结构:

type AppointmentsParticipants struct {
    AppointmentsID int `sql:",pk"`
    UserID int `sql:",pk"`
    Approved bool
    ReviewedAt time.Time
    ReviewedBy int
    Comment string
    Cancelled bool

}

type Appointments struct {
    ID int `sql:",pk"`
    Pending bool
    StartTime time.Time
    EndTime time.Time
    auditData
    InitialAppointmentID int
    SessionID string
    Type string
    AppointmentParticipants []*AppointmentsParticipants `json:"participants"`
}

我正在编写如下查询:

var app Appointments
err = database.DB().
        Model(&app).
        Column("*").
        Where("appointments_participants.user_id = ?", id).
        Join("JOIN appointments_participants ON appointments.id = appointments_participants.appointments_id").
        Select()

这确实会返回 Appointments 结构的所有值,但 AppointmentParticipants 切片除外。它返回一个空切片。我接受了 go-pg 编写的查询,并在 psql 中验证了它确实从约会参与者表中返回了一条记录。

这是输出:{140 true 2018-09-01 00:00:00 +0000 UTC 2018-09-01 01:00:00 +0000 UTC {2018-08-15 22:52:11.326775 +0000 UTC 5 0001-01-01 00:00:00 +0000 UTC 0} 0 Session []}

有趣的是,这个查询确实返回了一个错误:pg: can't find column=appointments_id in model=Appointments 但是我尝试使用 struct 标签来尝试解决这个问题,但无济于事。

【问题讨论】:

    标签: go go-pg


    【解决方案1】:

    试试这样的查询:

    err = database.DB().
        Model(&app).
        Column("AppointmentsParticipants").
        Relation("AppointmentsParticipants", func(q *orm.Query) (*orm.Query, error) {
            return q.Where("user_id = ?", id), nil
        }).
        Select()
    

    如果不行,尝试使用 ids,他们的字段名和标签,go-pg 对此非常敏感。

    【讨论】:

      最近更新 更多