0

I have 2 database table; A has 3 columns and they are X, Y, Z B has 2 columns and they are X, W

My Go structs are like this;

type Base struct {
    X int
    Y int
}

type A struct {
    Base
    Z int
}

type B struct {
    Base
    W int
}

And I initialize my structs like this;

    a := A{Base: Base{X: 1, Y:2}, Z: 3}
    b := B{Base: Base{X: 1}, W: 4}

When I want to insert these to database using gorm.io ORM, "a" is inserted without any problem but "b" can't be inserted because postgresql gives me an error something like

pq: column "y" of relation "B" does not exist

How can I insert "b" to database without creating another base model that doesn't have "Y" field?

3 Answers 3

1

When you assigning struct to another struct, and you create instance of struct, all struct fields has been filled with they default data-type value.

for example: int default value is 0.

So you have 2 solution for this question.

  1. create two different struct(without Base struct), just A and B. like this: (maybe you know this solution.).
type A struct {
    X int
    Y int
    Z int
}

type B struct {
    X int
    W int
}
  1. use struct tags to prevent from inserting with gorm.

Note: I didn`t test this.

type Base struct {
    X int 
    Y int `json:"y,omitempty"`
}

type A struct {
    Base
    Z int
}

type B struct {
    Base
    W int
}
2
  • 1
    Thank you for your reply but this doesn't solve my problem. In the question, I wanted to demonstrate a small example but in my project, I have more structs that have embedded Base struct. So your first solution doesn't solve the way I want(but this solution is better than creating another Base struct that doesn't have "Y"). And for your second solution, I tried this one before but it didn't work.
    – Omeerfk
    Aug 18, 2020 at 6:45
  • 1
    @Omeerfk I think another solution is using map[string]interface{}. then create dynamic query for that.
    – ttrasn
    Aug 18, 2020 at 6:53
0

I think you are not declaring the models correctly as documentation 'Base' should have tag embedded inside both A and B then it is ok. .. . for your better understanding I am posting your code with modification. Please be noted that I have tested in my machine it works as charm. .

here is the model declaration.

type Base struct {
    X int `json:"x"`
    Y int `json:"y"`
}

type A struct {
    Base `gorm:"embedded"`
    Z    int `json:"z"`
}

type B struct {
    Base `gorm:"embedded"`
    W    int `json:"w"`
}

here is the main function for your understanding. . .

func main() {
    fmt.Println("vim-go")
    db, err := gorm.Open("postgres", "host=localhost port=5432 user=postgres 
dbname=testd password=postgres sslmode=disable")
    if err != nil {
        log.Panic("error occured", err)
    }
    db.AutoMigrate(&A{}, &B{})

    a := &A{Base: Base{X: 1, Y: 2}, Z: 3}
    b := &B{Base: Base{X: 1}, W: 3}

    if err := db.Create(a).Error; err != nil {
        log.Println(err)
    }

    if err := db.Create(b).Error; err != nil {
        log.Println(err)
    }

    fmt.Println("everything is ok")
    defer db.Close()
 }

Please be sure to check the documentation of model declaration and the tags. . . gorm model declaration

Note: Y field will be there in B table but with zero value. . .

0
package main
import (
"encoding/json"
"fmt"
"reflect"
)
type SearchResult struct {
OrderNumber     string      `json:"orderNumber"`
Qunatity        interface{} `json:"qty"`
Price           string      `json:"price"`
OrderType       interface{} `json:"type"`
ItemQty         string      `json:"itemQty"`
}
type Or []SearchResult
func fieldSet(fields ...string) map[string]bool {
set := make(map[string]bool, len(fields))
for _, s := range fields {
    set[s] = true
}
return set
}
func (s *SearchResult) SelectFields(fields ...string) map[string]interface{} {
    fs := fieldSet(fields...)
    rt, rv := reflect.TypeOf(*s), reflect.ValueOf(*s)
    out := make(map[string]interface{}, rt.NumField())
    for i := 0; i < rt.NumField(); i++ {
        field := rt.Field(i)
        jsonKey := field.Tag.Get("json")
        if fs[jsonKey] {
            out[jsonKey] = rv.Field(i).Interface()
    }
   }
    return out
 }
 func main() {
    result := &SearchResult{
    Date:     "to be honest you should probably use a time.Time field here, 
    just sayin",
    Industry: "rocketships",
    IdCity:   "interface{} is kinda inspecific, but this is the idcity field",
    City:     "New York Fuckin' City",
}
    b, err := json.MarshalIndent(result.SelectFields("orderNumber", "qty"), "", "  ")
   if err != nil {
        panic(err.Error())
    }
    var or Or
    fmt.Print(string(b))
or=append(or,*result)
or=append(or,*result)
for i := 0; i < len(or); i++ {
c, err := json.MarshalIndent(or[i].SelectFields("idCity", "city", "company"), 
 "", "  ")
 if err != nil {
    panic(err.Error())
 }
 fmt.Print(string(c))
 }
 }

The one way of doing this using omitempty fields in struct and other way is to traverse through struct fields which is expensive. In case of performance doesn`t matter for you then you can take reference of above code snippet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.