Gorm: Help with join Query examples

Created on 14 Jan 2015  路  2Comments  路  Source: go-gorm/gorm

I need help with some join queries. In the provided User example,

a) How do I get all the Email records for the user with name "jinzhu"
Using

db.Model(&user).Related(&emails) 

assumes that I know the id of the user object. All I know is the name.

b) How do I get the BillingAddress of the User who has an email "[email protected]"

I know I can achieve both of these using raw sql but I was hoping that I could do this using gorm and with one query. Please let me know.

Thanks
-Rv

Most helpful comment

You have to use Joins then, you could write it like this:

db.Joins("left join users on users.id = emails.id").Where("users.name = ?", "jinzhu").Find(&emails) 

All 2 comments

You have to use Joins then, you could write it like this:

db.Joins("left join users on users.id = emails.id").Where("users.name = ?", "jinzhu").Find(&emails) 

Thanks

Was this page helpful?
0 / 5 - 0 ratings