search
HomeBackend DevelopmentGolangGolang sqlx convert right side of many to many join to array

Golang sqlx 将多对多连接的右侧转换为数组

php Editor Xigua will introduce to you in this article how Golang sqlx converts the right side of a many-to-many connection into an array. Golang is a powerful programming language, and sqlx is a popular Golang database tool. When using sqlx for many-to-many connections, we often need to convert the results on the right side into an array for easier processing and operation. This article will introduce in detail how to use sqlx and some examples to demonstrate this process. I hope it will be helpful to everyone.

Question content

I have two tables unit and unitimage with unit foreign key.

I execute this sql query

select un.*, array_agg(row(ui.is_main, ui.image, ui.id)) as unit_images
from unit un
inner join unitimage ui on ui.unit_id = un.id
group by un.id;

In response I got all the unit fields and joined the field unit_images like this

{"(f,photos/units/unit_37/90_big.jpg,108)","(f,photos/units/unit_37/91_big.jpg,109)","(f,photos/units/unit_37/92_big.jpg,110)","(f,photos/units/unit_37/93_big.jpg,111)"}

go language structure

type unit struct {
    id                     *int         `json:"id" db:"id"`
    name                   *string      `json:"name" db:"name"`
    ... a lot of fields
    unitimages             []unitimages `json:"unit_images" db:"unit_images"`
}

type unitimages struct {
    id *int `json:"id" db:"id"`
    image  *string `json:"image" db:"image"`
    ismain *bool   `json:"is_main" db:"is_main"`
}

sqlxcode

query := fmt.Sprintf("SELECT un.*, array_agg(ROW(ui.id, ui.image, ui.is_main)) as unit_images FROM %s un INNER JOIN %s ui ON ui.unit_id = un.id GROUP BY un.id",
unitsTable, unitImagesTable)
err := r.db.Select(&units, query)

I got the error"sql: Scan error on column index 45, name \"unit_images\": Scan not supported, storing driver.value of type []uint8 to type *[]*unitimages"

I am new to golang and I would like any tips on how to solve this problem. Maybe I chose the wrong way.

I would like to know the correct way to solve this problem.

Solution

It seems that the returned sql result is:

un.id | un.name | un.description | unit_images
------+---------+----------------+---------------------------------------------------------------------
1     | unit a  | description a  | [(true, 'image1.jpg', 1), (false, 'image2.jpg', 2), (false, 'image3.jpg', 3)]
2     | unit b  | description b  | [(true, 'image4.jpg', 4), (true, 'image5.jpg', 5), (false, 'image6.jpg', 6)]
3     | unit c  | description c  | [(true, 'image7.jpg', 7), (false, 'image8.jpg', 8), (false, 'image9.jpg', 9)]

so

`unitimages []unitimages `json:"unit_images" db:"unit_images"`

This is the correct idea, you have a unitimages array. but:

id *int `json:"id" db:"id"`
    image  *string `json:"image" db:"image"`
    ismain *bool   `json:"is_main" db:"is_main"`

Please note that id, image, is_main do not have sql columns, so go cannot map them.

Easy fix change unitimages to []any and then cast the contents into that array yourself like this:

for _, item := range thing.UnitImages {
  isMain := item[0].(bool)
  image := item[1].(string)
  id := item[2].(int64)

  //TODO do something with these vars
}

Or you could use `pg.StringArray` type.

The above is the detailed content of Golang sqlx convert right side of many to many join to array. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
Understanding Goroutines: A Deep Dive into Go's ConcurrencyUnderstanding Goroutines: A Deep Dive into Go's ConcurrencyMay 01, 2025 am 12:18 AM

GoroutinesarefunctionsormethodsthatrunconcurrentlyinGo,enablingefficientandlightweightconcurrency.1)TheyaremanagedbyGo'sruntimeusingmultiplexing,allowingthousandstorunonfewerOSthreads.2)Goroutinesimproveperformancethrougheasytaskparallelizationandeff

Understanding the init Function in Go: Purpose and UsageUnderstanding the init Function in Go: Purpose and UsageMay 01, 2025 am 12:16 AM

ThepurposeoftheinitfunctioninGoistoinitializevariables,setupconfigurations,orperformnecessarysetupbeforethemainfunctionexecutes.Useinitby:1)Placingitinyourcodetorunautomaticallybeforemain,2)Keepingitshortandfocusedonsimpletasks,3)Consideringusingexpl

Understanding Go Interfaces: A Comprehensive GuideUnderstanding Go Interfaces: A Comprehensive GuideMay 01, 2025 am 12:13 AM

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

Recovering from Panics in Go: When and How to Use recover()Recovering from Panics in Go: When and How to Use recover()May 01, 2025 am 12:04 AM

Use the recover() function in Go to recover from panic. The specific methods are: 1) Use recover() to capture panic in the defer function to avoid program crashes; 2) Record detailed error information for debugging; 3) Decide whether to resume program execution based on the specific situation; 4) Use with caution to avoid affecting performance.

How do you use the "strings" package to manipulate strings in Go?How do you use the "strings" package to manipulate strings in Go?Apr 30, 2025 pm 02:34 PM

The article discusses using Go's "strings" package for string manipulation, detailing common functions and best practices to enhance efficiency and handle Unicode effectively.

How do you use the "crypto" package to perform cryptographic operations in Go?How do you use the "crypto" package to perform cryptographic operations in Go?Apr 30, 2025 pm 02:33 PM

The article details using Go's "crypto" package for cryptographic operations, discussing key generation, management, and best practices for secure implementation.Character count: 159

How do you use the "time" package to handle dates and times in Go?How do you use the "time" package to handle dates and times in Go?Apr 30, 2025 pm 02:32 PM

The article details the use of Go's "time" package for handling dates, times, and time zones, including getting current time, creating specific times, parsing strings, and measuring elapsed time.

How do you use the "reflect" package to inspect the type and value of a variable in Go?How do you use the "reflect" package to inspect the type and value of a variable in Go?Apr 30, 2025 pm 02:29 PM

Article discusses using Go's "reflect" package for variable inspection and modification, highlighting methods and performance considerations.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment