gorm postgres queries elements in json array
gorm postgres Querying elements in a json array is a common need, especially when dealing with complex data structures. When using GORM for database queries, we can achieve this goal through some techniques. In this article, we will show you how to query elements in a json array using GORM and Postgres database. Whether you are a beginner or an experienced developer, this article will provide you with detailed guidance to help you solve this problem easily. let's start!
Question content
In my golang project, I use postgres with gorm and have an attribute column containing the following json:
{"email": ["[email protected]", "[email protected]", "[email protected]"], "mail_folder": "some_folder"} {"email": ["[email protected]", "[email protected]", "[email protected]"], "mail_folder": "some_folder"}
So I need to get the records containing the email [email protected]
, which is the first record. I can extract it using pure sql in sql editor using the following query:
select * from authors a where attributes @> '{"email": ["[email protected]"]}';
But in gorm I keep getting bad json syntax errors etc. I tried using raw() query or using
Where(fmt.Sprintf("attributes ->> 'email' = '[\"%v\"]'", email)).
But it doesn't work either. Any ideas on how to fix it would be welcome. Thanks.
Solution
sampledb in postgresql:
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 protected]</a>", "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="bccececefcdedede92dfdf">[email protected]</a>", "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="5d2929291d3e3e3e732727">[email protected]</a>" ], "mail_folder": "some_folder" }'), ('zzz', '{ "email": [ "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="0e7474744e6d6d6d206d6d">[email protected]</a>", "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="b3d2d2d2f3d1d1d19dd0d0">[email protected]</a>", "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="a7c5c5c5e7c4c4c489dddd">[email protected]</a>" ], "mail_folder": "some_folder" }');
This works fine:
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 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 }
For sample data printing:
1 eee {{"email": ["[email protected] ", "[email protected]", "[email protected] Protect]"], "mail_folder": "some_folder"}}
The above is the detailed content of gorm postgres queries elements in json array. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.
