Reputation: 141
I have a model like this:
type Course struct {
Name string `db:"course_name"`
}
type Group struct {
Course *Course
}
type Groups []Group
And when i try to do sqlx.Select for Groups with a query like this:
SELECT c.name as course_name FROM courses as c;
I get
missing destination name course_name in *main.Groups
error.
What is the issue with this code?
Upvotes: 6
Views: 22719
Reputation: 921
Ok, so when you are using an embbeded struct with Sqlx, capitalization is important, at least in my case.
You need to refer to the embedded struct in your sql, like so:
select name as "course.name" from courses...
Notice that course
is lower case and the naming involves a dot/period between table and column.
Then your Get
or Select
should work just fine.
Upvotes: 1
Reputation: 141
I changed Course *Course
to Course Course
- no effect.
When i made it embedded like this:
type Group struct {
Course
}
it worked.
This is also valid:
type Group struct {
*Course
}
Looks like sqlx doesn't understand anything except embedded fields.
Upvotes: 2
Reputation: 34286
You need to use sqlx.Select
when you are selecting multiple rows and you want to scan the result into a slice, as is the case for your query, otherwise use sqlx.Get
for a single row.
In addition, you can't scan directly into a Group
struct because none of its fields are tagged (unlike the Course
struct), and the Course
field isn't embedded.
Try:
course := Course{}
courses := []Course{}
db.Get(&course, "SELECT name AS course_name FROM courses LIMIT 1")
db.Select(&courses, "SELECT name AS course_name FROM courses")
Upvotes: 5