Home  >  Article  >  Backend Development  >  How Can I Efficiently Scan Nested Structs with sqlx?

How Can I Efficiently Scan Nested Structs with sqlx?

DDD
DDDOriginal
2024-11-23 08:55:11470browse

How Can I Efficiently Scan Nested Structs with sqlx?

Scanning into Nested Structs with sqlx

Nested structs present challenges when using sqlx. However, the documentation provides a solution through the use of embedded structs.

Embedded Structs

Sqlx supports embedded structs, allowing you to assign values to fields using Go's precedence rules for embedded attributes and methods.

Code Example

Consider the following code, where Address is not an embedded struct:

type Customer struct {
       Id      int     `json:"id" db:"id"`
       Name    string  `json:"name" db:"name"`
       Address Address `json:"adress"`
}

type Address struct {
       Street string `json:"street" db:"street"`
       City   string `json:"city" db:"city"`
}

This code will result in an error when attempting to scan into a Customer struct because the Address field is not embedded and does not have its own db tag.

To resolve this, embed Address into Customer:

type Customer struct {
   Id     int    `json:"id" db:"id"`
   Name   string `json:"name" db:"name"`
   Address
}

By embedding Address, its fields (including tags) are promoted into Customer, allowing sqlx to populate them from the query result.

JSON Output

Embedding Address will flatten the JSON output, as seen below:

{
    "id": 1,
    "name": "foo",
    "street": "bar",
    "city": "baz"
}

To address this, you can remap the DB struct to your original type or scan the query result into a map.

The above is the detailed content of How Can I Efficiently Scan Nested Structs with sqlx?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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