Kristijan Ujevic
Kristijan Ujevic

Reputation: 11

Scanning into struct of gorm models

I'm trying to scan the result of a query into a result structure that's comprised of gorm models.

The code builds and the query passes but the result array consists of default values like this:

{{0 0 0 0 0 0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0 0001-01-01 00:00:00 +0000 UTC { false}} {0 0 0 0 {0 false} {0 false} {0 false} 0001-01-01 00:00:00 +0000 UTC false {0 false} {0 false} { false} { false}}}

Also, result array has the exact length as the query result should have (when i try it manually through pgadmin) but they are not mapped correctly.

Is this possible or it's a gorm bug.

Code:

package main

import (
    "fmt"
    "test/model"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres"
)

type Result struct {
    model1    model.model1
    model2    model.model2
}

func main() {
    var result []Result
    var err error

    db, err := gorm.Open("postgres", "bla")
    defer db.Close()

    err = db.Raw(`SELECT t1.*, t2.*
                  FROM   t1
                   INNER JOIN t2 on something
                  WHERE something`).Scan(&result).Error

    for _, element := range result {
        fmt.Println(element)
    }
}

Upvotes: 1

Views: 10836

Answers (1)

Faisal AL Mahmud
Faisal AL Mahmud

Reputation: 550

You can use multiple Scan.

for example

type Dto1 struct {
    model1   model.model1
}

type Dto2 struct {
    model2    model.model2
}

func main() {

var dto1 []Dto1
var dto2 []Dto2
var err error

db, err := gorm.Open("postgres", "bla")
defer db.Close()

err = db.Raw(`SELECT t1.*, t2.*
              FROM   t1
               INNER JOIN t2 on something
              WHERE something`).Scan(&dto1).Scan(&dto2).Error

for _, element := range result {
    fmt.Println(element)
 }
}

Upvotes: 5

Related Questions