Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Left Join in Jinzhu GORM

Tags:

mysql

go

go-gorm

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

like image 664
Arthur Mastropietro Avatar asked Apr 16 '18 04:04

Arthur Mastropietro


People also ask

How join left join in SQL?

LEFT JOIN Syntaxcolumn_name = table2. column_name; Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.

How LEFT JOIN is used?

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.

What is left join and right join with example?

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.


1 Answers

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)

Note

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!

like image 104
RuNpiXelruN Avatar answered Oct 24 '22 03:10

RuNpiXelruN