type Book struct {
tableName struct{} `pg:"book" json:"-"`
Id int `pg:"id,pk" json:"id"`
Author int `pg:"author_id,notnull" json:"-"`
Author *Author `pg:"fk:author_id" json:"author,omitempty"`
}
I want select book and author in one query.
If I try this:
var r []model.Book
_, err := dao.FusedDb.Query(&r, `SELECT * FROM book b INNER JOIN author a on a.id = b.author_id`)
I get an error
pg: can't find column=name in model=Book (try discard_unknown_columns)
I wrote down a piece of code that I always use when I've to deal with this scenario. First, let me show the code and then I'll comment on the relevant parts:
Structs definition
The
BookandAuthorstructs represent the tables defined in my database.Resultis used to hold the fetched records through the query specified below.The query
The query is pretty straightforward. We only used the method
Queryon the SQL client opened at the beginning of themainfunction. Then, we've to defer a call to the methodCloseon therowsvariable to clean up.Scanning
The
formakes sure that we scan all of the rows retrieved with theQuerymethod. To understand if there are other rows to fetch we use the methodNextthat returns a bool value indicating whether or not there are other rows to scan.In the body of the
forwe declare a loop-scoped variable to hold the current record. Thanks to theScanmethod we'll be able to assign each column to the relative field of the struct.Lastly, we've to check for any error by invoking the method
Erron therowsvariable and handle it.Let me know if this clarifies your question, thanks!