卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35268本站已运行394

gorm postgres 查询 json 数组中的元素

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": [
    "[email protected]",
    "[email protected]",
    "[email protected]"
  ],
  "mail_folder": "some_folder"
}'),
       ('zzz', '{
         "email": [
           "[email protected]",
           "[email protected]",
           "[email protected]"
         ],
         "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": ["[email protected]"]}'")

    for _, a := range authors {
        fmt.Printf("%d %s %sn", 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"}}

卓越飞翔博客
上一篇: golang 上基于标头的版本控制
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏