Search code examples
sqlgogo-gorm

Return value of Gorm complex query


Let's say I have:

type A struct {
  ID   string `gorm:"primary_key"`
  Name string
}

type B struct {
  ID   string `gorm:"primary_key"`
  AId  string
  A    A `gorm:"foreignkey:AId"`
  Val  string
}

If I wanted to do a normal query on A or B, I can just expect the A or B struct back. But if I wanted to do a join, what struct should I expect in go?

For example if my query were:

select * from a join b on a.id = b.a_id;

What does GORM return as a struct?


Solution

  • Converting the query

    select * from a join b on a.id = b.a_id;
    

    into gorm:

    db.Tables("a").Select("a.id as aid, a.name as aname, b.id as bid, b.a_id as baid, b.val as bval").Joins("JOIN b ON a.id = b.a_id").Find(&result)
    

    We can just create a temporary result struct that houses all fields from both tables a and b.

    result := []struct {
        ID   string `db:"aid"`
        Name string `db:"aname"`
        BId  string `db:"bid"`
        AId  string `db:"baid"`
        Val  string `db:"bval"`
    }{}
    

    Then, repackage this result struct as needed, or return this struct for the client to use.