Structs Within Structs: A Guide to SQLX's Advanced Scanning
While using SQLX, you might encounter challenges scanning data into nested structs. Let's consider this example:
type Customer struct { Id int `json:"id" db:"id"` Name string `json:"name" db:"name"` Address Address `json:"adress"` // Oops, missing embedded property } type Address struct { Street string `json:"street" db:"street"` City string `json:"city" db:"city"` }
When attempting to scan data using this definition, you'll encounter this error:
missing destination name street in *models.Customer
Solution: Embrace Embedded Structs
The key to resolving this issue lies in understanding SQLX's deep scanning capabilities. As the documentation suggests, it supports embedding structs, promoting their fields into the parent struct. To achieve this, simply embed Address into Customer:
type Customer struct { Id int `json:"id" db:"id"` Name string `json:"name" db:"name"` Address Address }
Note that we removed the Address field's own db tag, as it's no longer a separate entity.
Caution: Flatten the JSON Output
However, embedding Address flattens the JSON output of the Customer struct, as both Name and City are now direct properties:
{ "id": 1, "name": "foo", "street": "bar", "city": "baz" }
Possible Alternatives
If this is not desired, there are several alternative approaches:
The above is the detailed content of How to Effectively Scan Nested Structs Using SQLX?. For more information, please follow other related articles on the PHP Chinese website!