0

I am new to golang gorm, and recently encountered an issue with Association.

The struct I created is:

type DeliveryItem struct {
  ..........
  Targets  []TargetType     `json:"targets" gorm:"foreignkey:FK"`
}

I create a struct called TargetType like this:

type TargetType struct {
    name            string
    FK      int             
}

So If i post some data that has an array of targets, it will store data to the delivery item table first (but without targets data), and it will store the targets into a separate table. Everything works with the above structure.

However if i create an anonymous field and put Targets inside the anonymous field, then gorm does not insert those targets data into the table. It looks like it does not recognize a relation between DeliveryItem and TargetType

Here is the sample that does not work (for simplicity I did not provide the exact code):

type DeliveryItem struct {
  ..........
  CommonDetails 
}

type CommonDetails struct {
  ................
  Targets  []TargetType     `json:"targets" gorm:"foreignkey:FK"`
}

type TargetType struct {
    name            string
    FK      int             
}

Did I miss anything for gorm tag to make it work or is Gorm not supporting such kind of behavior? I checked the gorm doc, and its only talk about the first one I provided which works, but I just want to is it possible to make the my failed case work?

1 Answer 1

0

I would be surprised if your failed case could work, as the structure of the underlying fields is fundamentally different. You can see the difference running the code sample below.

package main

import "fmt"

type DeliveryItemEmbedded struct {
    CommonDetails
}

type DeliveryItem struct {
    Targets []TargetType `json:"targets" gorm:"foreignkey:FK"`
}

type CommonDetails struct {
    Targets []TargetType `json:"targets" gorm:"foreignkey:FK"`
}

type TargetType struct {
    name string
    FK   int
}

func main() {

    targets := []TargetType{
        TargetType{
            name: "target 1",
            FK:   2,
        },
    }

    cd := CommonDetails{
        Targets: targets,
    }

    die := DeliveryItemEmbedded{
        cd,
    }

    di := DeliveryItem{
        Targets: targets,
    }

    fmt.Printf("embedded: %+v\n", die)
    fmt.Printf("non-embedded: %+v\n", di)
}

gives:

embedded: {CommonDetails:{Targets:[{name:target 1 FK:2}]}}
non-embedded: {Targets:[{name:target 1 FK:2}]}

I'm not familiar with how gorm works under the hood, but I would be surprised if it was able to resolve the CommonDetails indirection. Unfortunately I don't think using the embedding is going to work with gorm in this instance.

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