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
Book
andAuthor
structs represent the tables defined in my database.Result
is used to hold the fetched records through the query specified below.The query
The query is pretty straightforward. We only used the method
Query
on the SQL client opened at the beginning of themain
function. Then, we've to defer a call to the methodClose
on therows
variable to clean up.Scanning
The
for
makes sure that we scan all of the rows retrieved with theQuery
method. To understand if there are other rows to fetch we use the methodNext
that returns a bool value indicating whether or not there are other rows to scan.In the body of the
for
we declare a loop-scoped variable to hold the current record. Thanks to theScan
method 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
Err
on therows
variable and handle it.Let me know if this clarifies your question, thanks!