亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

go-gorm postgres 方言:管理 jsonb 插入和查找的結構以正確使用 json 標簽

go-gorm postgres 方言:管理 jsonb 插入和查找的結構以正確使用 json 標簽

Go
拉丁的傳說 2023-07-17 17:07:41
做了很多搜索,盡管我可以找到很多很好的文章來解釋如何直接使用 pq 包。我對 go-gorm 和 postgresql 方言的工作感到茫然。如果在checks.go中我使用ChecksMap,它不會讓我插入,但會讓我找到。如果我使用postgres.jsonb它可以讓我插入和查詢,但找到的記錄將是 jsonb。Gorm 使用指針的結構來確定數據庫表和模式。當使用從 API 返回 json 響應的通用 searchHandler 實用程序時,這會引起頭痛。對于任何非 jsonb 類型,gorm 使用正確的結構并使用 json 標簽,但對于 jsonb,因為它沒有對 jsonb 的“結構”的引用,所以不能使用 json 標簽。這會導致返回 API json 的鍵大寫。{   results: {      id: "123",      someId: "456",      results: [         {            Description: "foobar"         }      ]   }}是否有一種優雅的方法來處理此類事情,以便 jsonb 結果列具有正確的結構并使用小寫的 json 標簽?我只是想做一些在 go-gorm 的背景下不應該做的事情嗎?PostgreSQL DDLCREATE TABLE checks (   id        text,   some_id   text,   results   jsonb);檢查.gotype CheckRules struct {   Description   string `json:"description"`}type ChecksMap   map[string]CheckRulestype Checks struct {   ID            string           `gorm: "primary_key", json:"id"`   SomeID        *string          `json:"someId"`   Results       postgres.jsonb   `json:"results"`                   // <-- this   // results    ChecksMap        `gorm:"type:jsonb" json:"results"` // <-- or this}// func (cm *ChecksMap) Value() (driver.Value, error) {...}// func (cm *ChecksMap) Scan(val interface{}) error {...}insertChecks.govar resultsVal = getResultsValue() // simplifiedresJson, _ := json.Marshal(resultsVal)checks := Checks{   SomeID: "123",   Results: postgres.Jsonb{ RawMessage: json.RawMessage(resJson) }}err := db.Create(&checks).Error// ... some error handlinggetChecks.govar checks Checkserr := db.Find(&checks).Error// ... some error handling搜索處理程序func SearchHandler(db *gorm.DB, model, results interface{}) func(c echo.Context) error {   return func(c echo.Context) error {      err := db.Find(results).Error      // ... some error handling      jsnRes, _ := json.Marshal(results) // <-- uppercase "keys"      return c.JSON(http.StatusOK, struct {         Results interface{} `json:"results"`      }{         Results: string(jsnRes),      })   }}
查看完整描述

1 回答

?
米脂

TA貢獻1836條經驗 獲得超3個贊

您可以使用自定義類型,但在其值接收器而不是指針接收器上ChecksMap實現接口。driver.Valuer


所以,而不是:


func (cm *ChecksMap) Value() (driver.Value, error) { ...

你會這樣寫:


func (cm ChecksMap) Value() (driver.Value, error) {

    if cm == nil {

        return nil, nil

    }

    return json.Marshal(cm)

}

或者,您可以使其與指針實現一起使用,但隨后您必須將該字段轉換為指針,例如:


type Checks struct {

   ID      string     `gorm: "primary_key", json:"id"`

   SomeID  *string    `json:"someId"`

   Results *ChecksMap `json:"results"`

}

(雖然我還沒有測試過,所以我不能 100% 確定 gorm 將如何處理這種情況)


查看完整回答
反對 回復 2023-07-17
  • 1 回答
  • 0 關注
  • 293 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號