简体   繁体   English

在 GoLang 中使用 go-pgsql 从 postgresql 访问数据的正确方法

[英]Correct way to access data from postgresql using go-pgsql in GoLang

I've been reading the GoLang go-pgsql documentation in order to figure out how to access data with nested objects, but I have so far been unsuccessful.我一直在阅读GoLang go-pgsql文档以弄清楚如何使用嵌套对象访问数据,但到目前为止我还没有成功。

Here's the description of what I am trying to achieve:这是我要实现的目标的描述:

I have two models ClimateQuestions and Steps :我有两个模型ClimateQuestionsSteps

type ClimateQuestions struct {
    tableName struct{} `pg:"climatequestions"`
    Id        int      `json:"id" pg:",pk"`
    Title     string   `json:"title"`
    Steps     []*Steps  `pg:"rel:has-many"`
}

type Steps struct {
    tableName        struct{}          `pg:"steps"`
    Id               int               `json:"id"`
    Label            string            `json:"label"`
    Number           int               `json:"number"`
    QuestionId       int               `json:"question_id"`
}

and here is how they're defined in the database:这是它们在数据库中的定义方式:

CREATE TABLE climatequestions (
    id SERIAL PRIMARY KEY,
    title VARCHAR(255) NOT NULL
);

CREATE TABLE steps (
    id SERIAL PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    value DOUBLE PRECISION NOT NULL,
    question_id INT REFERENCES climatequestions(id)
);

And a relationship between these models is this: For every climate question, there can be many steps.这些模型之间的关系是这样的:对于每个气候问题,都可以有很多步骤。 I have denoted this by adding a field in ClimateQuestions struct called Steps with rel:has-many .我通过在ClimateQuestions结构中添加一个名为Steps with rel:has-many的字段来表示这一点。

Now, from the database, I would like to obtain all the climate questions, and within each of them, I want an array of steps data.现在,我想从数据库中获取所有的气候问题,并且在每个问题中,我想要一个步骤数据数组。

My first method to achieve this has been the following:我实现这一目标的第一个方法如下:

var climateQuestions []model.ClimateQuestions
err := db.Model(&climateQuestions).Select()

This partially works in that it returns all the data relevant for climate questions, but it does not add the nested steps data.这部分起作用,因为它返回与气候问题相关的所有数据,但不添加嵌套步骤数据。 Here is the JSON format of what is returned:这是返回内容的 JSON 格式:

[{"id":1,"title":"first question?","Steps":null},{"id":2,"title":"second question?","Steps":null}]

Any ideas as to how I may achieve this?关于如何实现这一目标的任何想法?

  1. Because you have custom join foreign key, you need to add tag pg:"rel:has-many,join_fk:question_id" in ClimateQuestions.Steps因为你有自定义连接外键,你需要在 ClimateQuestions.Steps 中添加标签pg:"rel:has-many,join_fk:question_id" ClimateQuestions.Steps
  2. In struct Steps , you need to tell pg which field it is.在 struct Steps中,您需要告诉 pg 它是哪个字段。
  3. You forgot to call Relation function你忘了打电话给Relation function

this is the correct struct这是正确的结构

type ClimateQuestions struct {
    tableName struct{} `pg:"climatequestions"`
    Id        int      `json:"id" pg:",pk"`
    Title     string   `json:"title"`
    Steps     []*Steps `pg:"rel:has-many,join_fk:question_id"`
}

type Steps struct {
    tableName  struct{} `pg:"steps"`
    Id         int      `json:"id"`
    Label      string   `json:"label" pg:"title"`
    Number     int      `json:"number" pg:"value"`
    QuestionId int      `json:"question_id"`
}


this is how you should exec db.这就是你应该如何执行数据库。

    var climateQuestions []ClimateQuestions
    err := db.Model(&climateQuestions).Relation("Steps").Select()
    if err != nil {
        panic(err.Error())
    }

    for _, v := range climateQuestions {
        fmt.Printf("%#v\n", v)
        for _, v1 := range v.Steps {
            fmt.Printf("%#v\n", v1)
        }
        fmt.Println("")
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何限制PostgreSQL(使用SQL和PL/pgSQL)只能通过某些存储过程来更改表数据的方式? - How to restrict in PostgreSQL (using SQL and PL/pgSQL) way of changing table data only by means of certain stored procedure? 从PostgreSQL获取数据的正确方法是什么? - What is the correct way to fetch data from PostgreSQL? 使用PGSQL()将Postgresql与星号连接 - Connecting postgresql with asterisk using PGSQL() 在 PL/PgSQL 中访问变量的数据 - Access data of variable in PL/PgSQL 将数据从一个应用程序中的 postgresql 数据库复制到 heroku 上另一个应用程序中的 postgresql 数据库的正确方法是什么? - What is the correct way to copy data from a postgresql database in one app to a postgresql database in another app on heroku? 如何使用 Golang 的 GORM 从 Postgresql 数据库中获取数组? - How to get an array from Postgresql database using Golang's GORM? PostgreSQL 和 Golang 之间的数据类型 - Data types between PostgreSQL and Golang 使用 python 以最快的方式从 postgresql 检索数据 - Retrieve data from postgresql in fastest way using python PL / pgsql正确在查询中动态转换regclass的方法 - PL/pgsql Correct way to cast regclass dynamically in query 如何将数据从非bdr pgsql迁移到bdr pgsql - How to migrate data from non-bdr pgsql to bdr pgsql
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM