Home > Article > Backend Development > 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!