繁体   English   中英

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

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

我一直在阅读GoLang go-pgsql文档以弄清楚如何使用嵌套对象访问数据,但到目前为止我还没有成功。

这是我要实现的目标的描述:

我有两个模型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"`
}

这是它们在数据库中的定义方式:

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

这些模型之间的关系是这样的:对于每个气候问题,都可以有很多步骤。 我通过在ClimateQuestions结构中添加一个名为Steps with rel:has-many的字段来表示这一点。

现在,我想从数据库中获取所有的气候问题,并且在每个问题中,我想要一个步骤数据数组。

我实现这一目标的第一个方法如下:

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

这部分起作用,因为它返回与气候问题相关的所有数据,但不添加嵌套步骤数据。 这是返回内容的 JSON 格式:

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

关于如何实现这一目标的任何想法?

  1. 因为你有自定义连接外键,你需要在 ClimateQuestions.Steps 中添加标签pg:"rel:has-many,join_fk:question_id" ClimateQuestions.Steps
  2. 在 struct Steps中,您需要告诉 pg 它是哪个字段。
  3. 你忘了打电话给Relation function

这是正确的结构

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"`
}


这就是你应该如何执行数据库。

    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM