簡體   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