I have a struct Person
:
type Person struct {
Id int64
Name string
Colors []string
}
which should get its data from a person
table:
id | name
---------
1 | Joe
2 | Moe
and a person_color
table:
person_id | color
-----------------
1 | black
1 | blue
2 | green
Via SELECT p.id, p.name, pc.color FROM person AS p INNER JOIN person_color AS pc ON pc.person_id = p.id
I merge both tables to:
id | name | color
-----------------
1 | Joe | black
1 | Joe | blue
2 | Moe | green
At the moment the only thing I could think of would be to manually map colors while iterating over rows.Next()
(NOTE: just dummy code):
ps := make([]People, 0)
rows, err := db.Query("SELECT ...")
for rows.Next() {
var p Person
err := rows.Scan(&p.Id, &p.Name, &p.Color[0])
exists := false
for _, ps := range ps {
if ps.Id == p {
exists = true
ps.Color = append(ps.Color, p.Color)
}
}
if !exists {
ps = append(ps, p)
}
}
Though this would work this is quite annoying as mapping to a slice field is a common operation.
Is there any way to make the above generic on all slice fields with sql or sqlx?