Golang:sqlx StructScan将数据库列映射到结构
我的模型结构如下所示:Golang:sqlx StructScan将数据库列映射到结构,go,Go,我的模型结构如下所示: type Detail struct { Product Stocks } type Product struct { Name string `db:"name"` Id int `db:"id"` } type Stocks { Name string `db:"name"` Price float `db:"price"`
type Detail struct {
Product
Stocks
}
type Product struct {
Name string `db:"name"`
Id int `db:"id"`
}
type Stocks {
Name string `db:"name"`
Price float `db:"price"`
Type string `db:"type"`
}
我将有一个查询来连接上面的表,如下所示:
query, args, err := sqlx.In("select p.name , s.price from Product p,Stocks s where p.name=s.name and type IN (?)",typecodes)
query = s.Cmd.Db.Rebind(query)
var rows *sqlx.Rows
rows, err = s.Cmd.Db.Queryx(query, args...)
for rows.Next() {
var p model.Detail
err = rows.StructScan(&p)
}
想知道我什么时候做行。StructScan(&p)是否会填充产品结构名称字段,或者是否会为相同的内容找到任何埋伏,因为股票也有名称字段
目前我没有得到任何上述结果。但当我在Stocks结构中注释Name字段时,我得到的是数据
让我知道我在这里遗漏了什么。对于不明确的字段,最好使用其结构名称的前缀对其进行注释,例如
产品名称
,股票名称
,然后在SQL语句中对其进行适当的别名
即。
在SQL中:
选择p.name作为产品名称,s.name作为库存名称。。。从产品p,库存s,其中。。。
对于模棱两可的字段,最好使用其结构名称的前缀对其进行注释,例如,产品名称
,股票名称
,然后在SQL语句中对其进行适当的别名。谢谢Martin。效果很好:)@MartinGallagher将其作为答案发布。没问题-完成!
type Detail struct {
Product
Stocks
}
type Product struct {
Name string `db:"product_name"`
Id int `db:"id"`
}
type Stocks {
Name string `db:"stock_name"`
Price float `db:"price"`
Type string `db:"type"`
}