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

发布于 2025-01-10 17:07:47 字数 1759 浏览 0 评论 0原文

我一直在阅读 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 结构中添加一个名为 Stepsrel: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}]

关于如何实现此目的有什么想法吗?

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.

Here's the description of what I am trying to achieve:

I have two models ClimateQuestions and Steps:

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.

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:

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

Any ideas as to how I may achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蝶舞 2025-01-17 17:07:47
  1. 因为您有自定义连接外键,所以需要在 ClimateQuestions.Steps
  2. 结构体 Steps 中添加标签 pg:"rel:has-many,join_fk:question_id",你需要告诉pg它是哪个字段。
  3. 您忘记调用 Relation 函数,

这是正确的结构,

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


这就是您应该如何执行 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("")
    }
  1. Because you have custom join foreign key, you need to add tag pg:"rel:has-many,join_fk:question_id" in ClimateQuestions.Steps
  2. In struct Steps, you need to tell pg which field it is.
  3. You forgot to call 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("")
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文