2

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.

4
  • 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. Commented Dec 29, 2016 at 10:55
  • Thanks Martin.It worked fine:) Commented Dec 29, 2016 at 11:36
  • @MartinGallagher Post that as an answer. Commented Dec 29, 2016 at 13:18
  • No problem - done! Commented Dec 29, 2016 at 13:23

1 Answer 1

3

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.

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:

SELECT p.name AS product_name, s.name AS stock_name, ... FROM Product p, Stocks s WHERE ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.