英文:
Golang: sqlx StructScan mapping db column to struct
问题
我有一个类似下面的模型结构:
type Detail struct {
Product
Stocks
}
type Product struct {
Name string `db:"name"`
Id int `db:"id"`
}
type Stocks struct {
Name string `db:"name"`
Price float64 `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)
}
想知道当我执行 rows.StructScan(&p)
时,Product 结构体的 Name 字段会被填充吗?还是会出现歧义,因为 Stocks 也有一个 Name 字段?
目前我没有得到上述查询的结果。但是当我注释掉 Stocks 结构体中的 Name 字段时,我可以得到数据。
请告诉我我在这里漏掉了什么。
英文:
i have my model struct like the below :
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"`
}
i would have a query to join the above tables like the below :
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)
}
Would like to know when i do rows.StructScan(&p) will the Product structure Name field be populated or will there be any ambuigity found for the same since Stocks also have a Name field ?
Currently i am not getting any result for the above.But when i comment the Name field in the Stocks struct, i am getting the data.
Let me know what i am missing here.
答案1
得分: 3
对于含糊不清的字段,最好在其结构名称前加上前缀进行注释,例如product_name
、stock_name
,然后在SQL语句中适当地使用别名。
例如:
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"`
}
在你的SQL语句中:
SELECT p.name AS product_name, s.name AS stock_name, ... FROM Product p, Stocks s WHERE ...
英文:
For ambiguous fields you're best annotating them with a prefix of their struct name, e.g. product_name
, stock_name
, then alias them appropriately in your SQL statement.
I.e.
<!-- language: go -->
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"`
}
And in your SQL:
<!-- language: sql -->
SELECT p.name AS product_name, s.name AS stock_name, ... FROM Product p, Stocks s WHERE ...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论