Arthur Mastropietro
Arthur Mastropietro

Reputation: 703

How to create a Left Join in Jinzhu 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

Upvotes: 7

Views: 16946

Answers (1)

RuNpiXelruN
RuNpiXelruN

Reputation: 1920

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!

Upvotes: 8

Related Questions