Sqlx "missing destination name" for struct tag through pointer

huangapple go评论88阅读模式
英文:

Sqlx "missing destination name" for struct tag through pointer

问题

我有一个像这样的模型:

type Course struct {
    Name string `db:"course_name"`
}

type Group struct {
    Course *Course
}
type Groups []Group

当我尝试使用以下查询对Groups进行sqlx.Select操作时:

SELECT c.name as course_name FROM courses as c;

我得到了一个错误信息:

> 在*main.Groups中缺少目标名称course_name

这段代码有什么问题?

英文:

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?

答案1

得分: 3

在选择多行并将结果扫描到切片中时,您需要使用sqlx.Select,这适用于您的查询情况,如果只选择一行,请使用sqlx.Get

此外,您不能直接将结果扫描到Group结构体中,因为它的字段没有标记(不像Course结构体),而且Course字段也没有嵌入。

请尝试以下代码:

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")
英文:

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")

答案2

得分: 1

我将Course *Course更改为Course Course,但没有效果。
当我像这样嵌入它时:

type Group struct {
    Course
}

它起作用了。

这也是有效的:

type Group struct {
    *Course
}

看起来sqlx除了嵌入字段之外,不理解其他任何东西。

英文:

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.

答案3

得分: 1

好的,当你在使用带有Sqlx的嵌入式结构时,大小写是很重要的,至少在我的情况下是这样。

你需要在sql中引用嵌入的结构,像这样:

select name as "course.name" from courses...

注意,course是小写的,并且命名中包含表和列之间的点/句号。

然后你的GetSelect应该可以正常工作。

英文:

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.

huangapple
  • 本文由 发表于 2017年7月8日 18:49:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/44985354.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定