Table of Contents
Question content
Solution
Home Backend Development Golang Golang sqlx convert right side of many to many join to array

Golang sqlx convert right side of many to many join to array

Feb 14, 2024 pm 02:48 PM

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;
Copy after login

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)"}
Copy after login

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"`
}
Copy after login

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)
Copy after login

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)]
Copy after login

so

`unitimages []unitimages `json:"unit_images" db:"unit_images"`
Copy after login

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"`
Copy after login

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.
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

See all articles