I can not create a simple query with a left join in jinzhu GORM (MySQL database)
These are my structs:
type Prop struct {
ID uint
Status Status
StatusID uint
Name string
}
type Status struct {
ID uint
Name string
}
Prop has a foreign key to Status
The SQL query i would like to perform is:
SELECT * from prop LEFT JOIN status ON prop.status_id = status.id
So i would retrieve all records from prop table joined with status table
I tried:
db.Find(&prop).Related(&status)
but no Success. Anyone has some advice? Thanks in advance
LEFT JOIN Syntaxcolumn_name = table2. column_name; Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.
A join combines the set of two tables only. A left join is used when a user wants to extract the left table's data only. Left join not only combines the left table's rows but also the rows that match alongside the right table.
The LEFT JOIN includes all records from the left side and matched rows from the right table, whereas RIGHT JOIN returns all rows from the right side and unmatched rows from the left table.
Hey @arthur_mastropietro,
I think Preloading the Prop
's related Status
is the key. Try the below:
prop := Prop{}
if err := db.Model(&prop).Preload("Status").Find(&prop).Error; err != nil {
fmt.Println(err)
}
fmt.Printf("%+v\n", prop)
You can chain the preloading of other structs, ie
Preload("Status").Preload("Something").
..etc. In fact you can chain most Gorm
function calls.
Additionally, if Status
was to also have another struct as one of it's fields you can load them both at once by calling
Preload("Status.Something")
Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With