簡體   English   中英

如何用go-pg查詢一對多關系

[英]How to query a one to many relationship with go-pg

我想查詢一對多的關系。 我有以下結構:

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()

這確實返回了Appointment結構的所有值,但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標記來嘗試解決此問題,但無濟於事。

嘗試這樣查詢:

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

如果不起作用,請嘗試使用ID,其字段名稱和標簽,go-pg對這一點非常敏感。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM