mailru / dbr

Additions to Go's database/sql for super fast performance and convenience. (fork of gocraft/dbr)
MIT License
178 stars 36 forks source link

Unmarshaling joins? #6

Closed nkev closed 7 years ago

nkev commented 7 years ago

Nice work! I was just playing with this and couldn't work out how to unmarshal joined tables. For example, in your example:

sess.Select("*").From("suggestions").
  Join("subdomains", "suggestions.subdomain_id = subdomains.id")

How would you store the query result into a struct using .Load(&suggestions) that contains []subdomain field?

bgaifullin commented 7 years ago

Hi. Thanks.

The result of your query will contains all columns from tables suggestions and subdomains.

dbr does not unmarshal join result into separate array in result.

You should pass into load struct SugestionsAndSubdomains, which contains both fields for columns from suggestions and from subdomains. An appropriate name of column from query result can be specified by using tag 'db'.

See example:

// By default dbr converts CamelCase property names to snake_case column_names
// You can override this with struct tags, just like with JSON tags
// This is especially helpful while migrating from legacy systems
type SuggestionAndSubDomains struct {
    Id        int64
    Title     dbr.NullString `db:"subject"` // subjects are called titles now
         Domain string             `db:"domain"` // fields from table subdomains
}

var suggestionsWithSubdomains [] SuggestionAndSubDomains
sess.Select("*").From("suggestions").
    Join("subdomains", "suggestions.subdomain_id = subdomains.id").
    Load(&suggestionsWithSubdomains)