首頁 > 後端開發 > Golang > 主體

gorm postgres 查詢 json 陣列中的元素

PHPz
發布: 2024-02-10 18:50:08
轉載
410 人瀏覽過

gorm postgres 查询 json 数组中的元素

gorm postgres 查詢 json 陣列中的元素是一個常見的需求,特別是在處理複雜的資料結構時。在使用 GORM 進行資料庫查詢時,我們可以透過一些技巧來實現這個目標。在本文中,我們將向您展示如何使用 GORM 和 Postgres 資料庫來查詢 json 陣列中的元素。無論您是初學者還是有經驗的開發者,本文都將為您提供詳細的指導,以幫助您輕鬆解決這個問題。讓我們開始吧!

問題內容

在我的 golang 專案中,我將 postgres 與 gorm 結合使用,並且有一個包含以下 json 的屬性列:

{"email": ["[email protected]", "[email protected]", "[email protected]"], "mail_folder": "some_folder"}
{"email": ["[email protected]", "[email protected]", "[email protected]"], "mail_folder": "some_folder"}
登入後複製

所以我需要取得包含電子郵件 [email protected] 的記錄,這是第一筆記錄。我可以使用以下查詢在 sql 編輯器中使用純 sql 來提取它:

select * from authors a where attributes @> '{"email": ["[email protected]"]}';
登入後複製

但在 gorm 中,我不斷收到錯誤的 json 語法錯誤等。我嘗試使用 raw() 查詢或使用

Where(fmt.Sprintf("attributes ->> 'email' = '[\"%v\"]'", email)).
登入後複製

但它也不起作用。任何如何修復它的想法都將受到歡迎。謝謝。

解決方法

postgresql 中的 sampledb:

create table authors
(
    id         serial,
    dummy      text,
    attributes jsonb
);

insert into authors (dummy, attributes)
values ('eee', '{
  "email": [
    "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="0762626247646464296464">[email&#160;protected]</a>",
    "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="bccececefcdedede92dfdf">[email&#160;protected]</a>",
    "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="5d2929291d3e3e3e732727">[email&#160;protected]</a>"
  ],
  "mail_folder": "some_folder"
}'),
       ('zzz', '{
         "email": [
           "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="0e7474744e6d6d6d206d6d">[email&#160;protected]</a>",
           "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="b3d2d2d2f3d1d1d19dd0d0">[email&#160;protected]</a>",
           "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="a7c5c5c5e7c4c4c489dddd">[email&#160;protected]</a>"
         ],
         "mail_folder": "some_folder"
       }');
登入後複製

這工作正常:

package main

import (
    "fmt"
    postgres2 "github.com/jinzhu/gorm/dialects/postgres"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
    "log"
)

var (
    dsn = "host=localhost user=postgres password=secret dbname=sampledb port=5432 sslmode=disable TimeZone=europe/istanbul"
)

type Author struct {
    Id         int `gorm:"primaryKey"`
    Dummy      string
    Attributes postgres2.Jsonb `gorm:"type:jsonb;default:'{}'"`
}

var DB *gorm.DB

func main() {
    DB = initDb()
    listAuthors()
}

func listAuthors() {
    var authors []Author
    DB.Find(&authors, "attributes @> '{\"email\": [\"<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="95f0f0f0d5f6f6f6bbf6f6">[email&#160;protected]</a>\"]}'")

    for _, a := range authors {
        fmt.Printf("%d %s %s\n", a.Id, a.Dummy, a.Attributes)
    }
}

func initDb() *gorm.DB {
    db, err := gorm.Open(postgres.Open(dsn))
    if err != nil {
        log.Fatal("couldn't connect to db")
    }
    return db
}
登入後複製

對於範例資料列印:

1 eee {{"email": ["[電子郵件受保護] ", "[電子郵件受保護]", "[電子郵件受保護]"], "mail_folder": "some_folder"}}

以上是gorm postgres 查詢 json 陣列中的元素的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!