Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GORM JOINs and Results

Tags:

join

go

go-gorm

Suppose I have two tables, which share some column names such as:

table_1
    - id
    - created_at
    - deleted_at
    - name
    - color

table_2
    - id
    - created_at
    - deleted_at
    - address
    - name

When I run a join query on these two tables I get something back like this:

id, created_at, name, color, id, created_at, deleted_at, address, name

I have 2 structs resembling the models I described above. Now I want to scan the results into a results struct:

type Result struct {
   Model1
   Model2
}

I then use db.Raw().Scan(&result). Now the Problem: The id of table_2 is never written into the struct for table 2, only into the struct of table 1 in the results struct.

My question is: how can I read the results of a JOIN query into a results struct, when there are columns named the same.

like image 208
jjuser19jj Avatar asked Oct 24 '18 05:10

jjuser19jj


1 Answers

I don't know whether this was possible in Gorm V1, but in V2 you can use Embedded Structs with a prefix to disambiguate the two result sets, you can then name the columns appropriately to direct them to the right embedded model:

type Model1 struct {
    ID    int `gorm:"primaryKey"`
    Value string
}

type Model2 struct {
    ID    int `gorm:"primaryKey"`
    Value string
    Color string
}

type Result struct {
    Model1 `gorm:"embedded;embeddedPrefix:m1_"`
    Model2 `gorm:"embedded;embeddedPrefix:m2_"`
}

res := Result{}
db.Raw(`
    SELECT
        1 AS m1_id,
        'one' AS m1_value,
        2 AS m2_id,
        'two' AS m2_value,
        'rose' AS m2_color
`).Scan(&res)

fmt.Printf("%+v\n", res)
// {Model1:{ID:1 Value:one} Model2:{ID:2 Value:two Color:rose}}
like image 155
Ezequiel Muns Avatar answered Sep 23 '22 02:09

Ezequiel Muns