2

简而言之,我的问题是:我可以使用 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;`
}

使用 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.
}

我可能有这样的功能:

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     
}

我可以填写一个电话号码,但不能同时填写。我不确定我是否正确理解了别名说明。

我会很感激任何见解。

谢谢。

4

0 回答 0