简而言之,我的问题是:我可以使用 sqlx 的 StructScan 用来自连接两次的同一个 SQL 表的值填充两个嵌入式结构吗?
有用的 sqlx 包的帮助文件说明了这一点:
StructScan 将在 Person.AutoIncr.ID 中设置 id 列结果,也可以通过 Person.ID 进行访问。为了避免混淆,建议您使用 AS 在 SQL 中创建列别名。
假设我有这个 SQL 查询(父子、人到电话):
func getSQL() string {
return `SELECT *
FROM person
LEFT JOIN phones AS Phone1 ON Phone1.phone_id = person_phoneID1
LEFT JOIN phones AS Phone2 ON Phone2.phone_id = person_phoneID2
WHERE people_id = 1;`
}
Run Code Online (Sandbox Code Playgroud)
使用 sqlx 和 StructScan,我想填充一个充满嵌入式结构的结构,如下所示:
//Struct with embedded structs
type personHelper struct{
Person
Phone1 //Should I use the same name as SQL table alias?
Phone2
}
type Phone1 struct {
Phone //Underlying struct
}
type Phone2 struct{
Phone
}
//Base structs, with tags to match up fields
type Person struct{
ID `db:"person_id"`
Name `db:"person_name"`
Phone1 `db:"person_phoneID1"`
Phone2 `db:"person_phoneID2"`
}
type Phone struct{
ID int64 `db:"phone_id"`
Number string `db:"phone_no"`
//etc.
}
Run Code Online (Sandbox Code Playgroud)
我可能有这样的功能:
func getPeople(){
parseRows := func(rows *sqlx.Rows) {
for rows.Next() {
var ph personHelper
err := rows.StructScan(&ph)
if err != nil{
//etc.
}
}
}
sql := getSQL()
sqlutils.GetRows(parseRows, sql)//GetRows executes the SQL query and returns rows for processing
}
Run Code Online (Sandbox Code Playgroud)
我可以填写一个电话号码,但不能同时填写两个。我不确定我是否正确理解了别名指令。
我将不胜感激任何见解。
谢谢。