登录
首页 >  Golang >  Go问答

查询 go-pg 中的一对多关系

来源:stackoverflow

时间:2024-03-22 20:09:31 303浏览 收藏

在 Go-pg 中查询一对多关系时,通过 Join 语句连接表可以返回目标结构的所有值,但关联表字段返回空切片。通过使用 Relation 方法指定关联查询条件,可以正确获取关联表数据。需要注意的是,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()

这确实返回 appointments 结构的所有值(appointmentparticipants 切片除外)。它返回一个空切片。我已经采取了 go-pg 写入的查询并在 psql 中验证它确实从 appointment_participants 表返回一条记录。

这是输出:{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 会话 []}

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


解决方案


尝试这样的查询:

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 对此非常敏感。

到这里,我们也就讲完了《查询 go-pg 中的一对多关系》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>